Warning C26487

Don't allow a function to return an invalid pointer, either through a formal return statement or through output parameters.

int* ex1(int a)
{
  return &a;     // returns a dangling pointer to the stack variable 'a'
}

void ex2(int a, int** out)
{
  *out = &a;    // 'out' contains a dangling pointer to the stack variable 'a'
}

Remarks

The Lifetime guidelines from the C++ Core Guidelines outline a contract that code can follow which enables more thorough static memory leak and dangling pointer detection. The basic ideas behind the guidelines are:

  • Never dereference an invalid (dangling) or known-null pointer.
  • Never return, either by formal return statement or out parameter, any dangling pointer from a function.
  • Never pass an invalid (dangling) pointer to any function.

An invalid pointer is dangling when it points to something that isn't there anymore. For example, any pointer to a local variable or parameter, once it's gone out of scope. Or, a pointer to a resource that's been deleted. Even a pointer to a static can be dangling, if the value gets changed before it can be used. A dangling pointer was once valid; that's what distinguishes it from other kinds of invalid pointers, such as an uninitialized pointer, or nullptr.

See also