申请内存时,C语言中有malloc函数,c++有更高级的new操作符。
new的其中一个特性就是可以注册一个内存申请失败的hook函数。
例如:在C++中我们可以调用_set_new_handler(),来设置一个"Allocation failure handler"函数,每当new申请内存失败时,这个函数就会被调用。而malloc默认并不支持这一特性。
有时需要将用C写的项目移植到C++上,通常不会用C++重写全部代码,保留C原来的功能带代码,新的功能才使用C++去写,但是在旧的C代码中malloc被广泛使用,但是又必须hook malloc申请内存失败的情况,该怎么办呢?
默认情况下malloc申请失败时不会调用new操作符的hook处理函数。但是可以通过_set_new_mode(),让malloc申请失败时也去调用hook处理函数。
下面是demo:
#include "stdafx.h"
#include "new.h"
#include <windows.h>
// Memory allocation failure handler.
int AllocationFailureHandler(size_t)
{
// Do what ever you wish
return 1;
}
int _tmain(int argc, _TCHAR* argv[])
{
/// Set the NewHandler and try "new" allocation failures.
// The NewHandler will be called.
_set_new_handler(AllocationFailureHandler);
char* pAllocatedByNew = new char[0x7fffffff];
// Check malloc. By default it won't call
// newHandler on failure.
char* pAllocatedByMalloc = (char*)malloc(1000000000000);
// Enable allocation failure reporting for malloc.
// and try once again. This time, NewHandler is called!
_set_new_mode(1);
pAllocatedByMalloc = (char*)malloc(1000000000000);
return 0;
}
注意:
如果你使用在MFC项目中注册了一个NewHandler函数,将会覆盖掉MFC默认的内存申请失败处理函数。