Share via


警告 C26816

指针指向堆栈上已分配的内存 (ES.65)

备注

指针指向堆栈上分配的变量。 当变量超出范围时,将会被清理,这会导致指针无效。

此检查可识别 C++ 标准模板库 (STL) 中的视图和所有者。 要教授此检查用户创作的类型,请使用 [[msvc::lifetimebound]] 批注。 [[msvc::lifetimebound]] 支持是 MSVC 17.7 中的新增功能。

代码分析名称:LIFETIME_LOCAL_USE_AFTER_FREE_STACK

示例

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

解决方法是延长所用值的生存期。 在此示例中,我们将通过返回 std::string 来解决警告。 也可以通过将数据复制到堆或向函数参数列表添加“out”变量来解决此问题。

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

另请参阅

C26815
ES.65:不要取消引用无效指针