Abh*_*Jha 1 c++ warnings pointers new-operator dynamic-memory-allocation
我试图学习 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)'
Run Code Online (Sandbox Code Playgroud)
我的代码:
#include <iostream>
#include <cstdint>
int main()
{
int* ptr = nullptr;
if (!ptr) {
ptr = new (std::nothrow) int32_t;
*ptr = 10;
}
std::cout << *ptr << "\n";
}
Run Code Online (Sandbox Code Playgroud)
new (std::nothrow) int32_t
Run Code Online (Sandbox Code Playgroud)
尝试为 分配内存int32_t,如果不能,则不会抛出异常,而是返回nullptr。
您继续为其分配一个数字(10),但您需要首先通过检查是否成功来确定内存分配是否成功ptr分配该值之前,您需要首先通过检查是否为 nullptr 来确定内存分配是否成功。它试图告诉您需要进行一些错误检查。
当你打印出来时也是同样的情况,它可能是一个 nullptr,你需要检查它。