我試圖在 C 中學習動態記憶體分配。我的程式可以編譯并運行,但 Visual Studio 向我拋出這些警告。
他們的意思是什么?
Warning C28193 'ptr' holds a value that must be examined.
Warning C28182 Dereferencing NULL pointer. 'ptr' contains the same NULL value as
'new(1*4, nothrow)'
我的代碼:
#include <iostream>
#include <cstdint>
int main()
{
int* ptr = nullptr;
if (!ptr) {
ptr = new (std::nothrow) int32_t;
*ptr = 10;
}
std::cout << *ptr << "\n";
}
uj5u.com熱心網友回復:
new (std::nothrow) int32_t
嘗試為 分配記憶體int32_t,如果不能,則不會拋出例外,而是回傳nullptr。
您繼續并為其分配一個數字 (10),但您需要ptr在分配值之前首先通過檢查是否為 nullptr來確定記憶體分配是否成功。它試圖告訴您您需要進行一些錯誤檢查。
當你列印出來時,它可能是一個 nullptr,你需要檢查它。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/373603.html
上一篇:C 編譯器如何發現運算子多載?
