共用方式為


警告 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:不要取值不正確指標