Issue 96403
Summary False positive "reference to stack memory associated with local variable" when double-dereferencing ("**itOpt") an optional iterator
Labels
Assignees
Reporter smcpeak
    For the following example:

```cpp
// test.cc
// Clang complains when accessing an optional iterator.

#include <cassert> // assert
#include <iostream>                    // std::cout
#include <optional>                    // std::optional
#include <vector> // std::vector

typedef std::vector<int> IVec;
IVec ivec;

int const &getVecElementRef()
{
  // Get a valid iterator.
  IVec::const_iterator it = ivec.cbegin();
  assert(it != ivec.end());

  // Wrap it in an optional.
 std::optional<IVec::const_iterator> itOpt(it);
  assert(itOpt);

#if 1
  // Access the iterator via double dereference.
  //
  // Clang complains: warning: reference to stack memory associated with
  // local variable 'itOpt' returned [-Wreturn-stack-address]
  return **itOpt;

#else
  // This works fine (with or without the `const &` part).
  auto const &tmp = *itOpt;
  return *tmp;
#endif
}

int main()
{
  ivec.push_back(0);

 // Get an element reference using operator[].
  int const &v0 = ivec[0];
  std::cout << "&v0: " << &v0 << "\n";

  // Get an element reference using the function.  The resulting address
  // is the same.
  int const &v1 = getVecElementRef();
  std::cout << "&v1: " << &v1 << "\n";

  // Returns 0.
  return v1;
}

// EOF
```

Clang (v16, v18, and latest) erroneously complains:

```text
$ clang++ -o test.exe  -std=c++17 -g -Wall test.cc
test.cc:27:12: warning: reference to stack memory associated with local variable 'itOpt' returned [-Wreturn-stack-address]
  return **itOpt;
           ^~~~~
1 warning generated.

$ ./test.exe
&v0: 0x5633e9c95eb0
&v1: 0x5633e9c95eb0
```

GCC and MSVC accept this example without complaint (https://godbolt.org/z/f49P4s4fd).

The consensus on StackOverflow is this is a false positive: https://stackoverflow.com/questions/78656796/is-it-ok-to-double-dereference-itopt-an-optional-iterator

_______________________________________________
llvm-bugs mailing list
llvm-bugs@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/llvm-bugs

Reply via email to