Warning C26816

The pointer points to memory allocated on the stack (ES.65)

Remarks

The pointer points to a variable that is allocated on the stack. When the variable goes out of scope it's cleaned up, which causes the pointer to be invalid.

Code analysis name: LIFETIME_LOCAL_USE_AFTER_FREE_STACK

Example

// In this example, std::string is being used internally because the implementer felt it was easier to
// perform the non-trivial initialization of the value but the function returns a C-style string.
const char *danglingRawPtrFromLocal() {
  std::string s;
  
  // interesting string initialization here
  
  return s.c_str(); // Oops, The pointer points to memory allocated on the stack
}

The fix is to extend the life of the value that is used. In this example, we address the warning by returning the std::string. It could also be addressed by copying the data to the heap or adding an "out" variable to the function parameter list.

std::string danglingRawPtrFromLocal() {
  std::string s;
  
  // interesting string initialization here
  
  return s;
}

See also

ES.65: Don't dereference an invalid pointer