关于在vc6.0中使用set_new_handler的问题
当运算符new找不到足够大的连续内存块来为对象分配内存时将会发生什么?一个称为 new-handler的函数被调用。
对于new-handler的缺省动作是抛出一个异常。然而,如果我们在程序里用堆分配,至少要用“内存已用完”的信息代替 new-handler,并异常中断程序。用这个办法,在调试程序时会得到程序出错的线索。
出错的代码例子
#include <iostream>
#include <new>
using namespace std;
void NoMoreMemory()
{
cerr << "Unable to satisfy request for memory\n";
abort();
return 0;
}
int main (int argc, char* argv[])
{
set_new_handler(NoMoreMemory);
int *pBigDataArray = NULL;
pBigDataArray = new int [100000000000000 * 1000000000000];
if(NULL == pBigDataArray)
{
cout << "alloc memory failed!" << endl;
}
else
{
delete pBigDataArray;
}
return 0;
}
vc6.0编译器报错
Assertion failed: new_p == 0, file setnewh.cpp, line 52
错误原因
原来是vc6.0编译器没有实现c++标准的set_new_handler()。vc6.0建议使用<new.h>中定义的_set_new_handler()。vc6.0为了防止用户使用set_new_handler()函数,在<setnewh.cpp> 的set_new_handler() 中插入了一行 assert(new_p == 0);
解决方法
将set_new_handler()换成 _set_new_handler()。将回调函数声明类型修改为int __cdecl noMemory(unsigned int anc)
修改正确的代码例子
#include <iostream>
#include <new.h>
using namespace std;
int __cdecl NoMoreMemory(unsigned int)
{
cerr << "Unable to satisfy request for memory\n";
abort();
return 0;
}
int main (int argc, char* argv[])
{
_set_new_handler(NoMoreMemory);
int *pBigDataArray = NULL;
pBigDataArray = new int [100000000000000 * 1000000000000];
if(NULL == pBigDataArray)
{
cout << "alloc memory failed!" << endl;
}
else
{
delete pBigDataArray;
}
return 0;
}
本文详细介绍了在VC6.0中如何使用_set_new_handler()函数替代标准库中的set_new_handler(),解决内存分配失败时的异常处理问题。通过提供自定义的回调函数,可以捕获内存不足的情况并给出更具体的错误信息,有助于程序调试。

3085

被折叠的 条评论
为什么被折叠?



