我已经申请了高分辨率的图像。
当我想要分配大量内存时,系统会说“应用程序已请求运行时以一种不寻常的方式终止它”。但我想要的是,分配的指针必须返回0或空,我才能显示我的消息。它不返回零/NULL为什么?有什么想法吗?在进入MessageBox之前,我检查了一下debug,它给出了这个错误。如何在此处显示我的消息?
有没有一种方法可以检查用户分配的内存是否比计算机PC容量大?
谢谢。
ImageW = 2000;
ImageH = 2000;
point *Img = NULL;
Img = new point[ImageW*ImageH];
if(Img== NULL)
{
MessageBox(0, "Your computer memory is too small.", "Error", MB_ICONERROR | MB_OK);
return;
}发布于 2012-10-16 09:59:08
发布于 2012-10-16 09:54:45
与C中的malloc在失败时返回NULL不同,C++中的new可以抛出std::bad_alloc异常,这就是您所看到的。有关参考,请参阅http://en.cppreference.com/w/cpp/memory/new/operator_new
要处理此异常,可以使用try/catch:
try {
Img = new point[ImageW*ImageH];
}
catch (std::bad_alloc const& e) {
// handle failure here, like displaying a message
}下面是std::bad_alloc异常的文档:http://en.cppreference.com/w/cpp/memory/new/bad_alloc
发布于 2012-10-16 09:55:51
C++ " new“在失败时不会返回null,它会调用新的处理程序。
https://stackoverflow.com/questions/12906469
复制相似问题