Muokkaa

Jaa


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.

This check recognizes views and owners from the C++ Standard Template Library (STL). To teach this check about user-authored types, use the [[msvc::lifetimebound]] annotation. The [[msvc::lifetimebound]] support is new in MSVC 17.7.

Code analysis name: LIFETIME_LOCAL_USE_AFTER_FREE_STACK

Examples

// 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 that will be cleaned up upon return. Warning C26816.
}

struct Y { int& get() [[msvc::lifetimebound]]; };
int& f() {
    Y y;
    return y.get(); // Warning C26826
}

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;
}

struct Y { int& get() [[msvc::lifetimebound]]; };
int f() {
    Y y;
    return y.get();
}

See also

C26815
ES.65: Don't dereference an invalid pointer