重载new 运算符后,把内存分配插入map 时,感觉像死循环了,然后产生了一个core,不得其解?

#include
#include
#include
#include
#include
#include
#include
#include

using namespace std;

typedef map GDB_MAP;

GDB_MAP g_map;
int cnt = 1;

#define SAFE_NEW new

void *operator new(size_t size)
//void *do_new(size_t size)
{
cout << "operator new called, " <<"file:" << FILE << "line=" << LINE<< endl;
void *p = NULL;
p = malloc(size);
memset(p, 0, sizeof(size));
g_map.insert(std::pair(p, cnt)); //为什么出错在这里??
//如果不重载new,则这个insert 就没问题
return p;
}

void operator delete(void *p)
//void do_delete(void *p)
{
GDB_MAP ::iterator iter;
cout << "operator delete called" << endl;
#if 1
iter = g_map.find(p);
if(iter == g_map.end())
{
cout << "fail to find the mem"<< endl;
return;
}
g_map.erase(iter);
#endif
free(p);
p = NULL;
}

int main(int argc, char *argv[])
{
int *pa = (int *)new int;
cout << "pa = "<< pa << endl;
delete(pa);
cout << "pa = "<< pa << endl;
return 0;
}

map的insert方法会调用到你重写的new方法,new 一个pair对象,所以一直是死循环调用了。
如果你想要重写new方法的话,最好将new 重写到类的方法中去,这样就不会影响其他类的new了。

但是我就是想用全局的重载

从输出的异常的log来看,确实是这个全局重载的new 发生了递归,死循环了

你声明GDB_MAP g_map;这个的时候就已经触发了new 重载。死循环了,这么干肯定不行,用c++类重载啊。或者加命名空间重载new,想用的话加命名空间的new。

using namespace std;

typedef list GDB_MAP;

GDB_MAP g_map;
int cnt = 1;

//#define SAFE_NEW MM_GDB::new
namespace MM_GDB
{
void *operator new(size_t size)
{
cout << "operator new called, " <<"file:" << FILE << "line=" << LINE<< endl;
std::list::iterator it;
void *p = NULL;
p = malloc(size);
memset(p, 0, sizeof(size));
it = g_map.begin();
g_map.insert(it, p);
return p;
}

void operator delete(void *p)
{
GDB_MAP ::iterator iter;
cout << "operator delete called" << endl;
g_map.remove(p);
free(p);
p = NULL;
}

}

#define SAFE_NEW MM_GDB::new
using namespace MM_GDB;
int main(int argc, char *argv[])
{
int *pa = SAFE_new int(10);

cout << "pa = "<< pa << endl;
delete(pa);
cout << "pa = "<< pa << endl;
return 0;

}

~

~

~

~

~

~

~

~

~

~

~

"xxx.cpp" 58L, 976C written

[song_kuang@NGFW-PKG ~]$ g++ -g -o xxx xxx.cpp
xxx.cpp:21: error: ‘void* MM_GDB::operator new(size_t)’ may not be declared within a namespace
xxx.cpp:34: error: ‘void MM_GDB::operator delete(void*)’ may not be declared within a namespace
xxx.cpp: In function ‘int main(int, char**)’:
xxx.cpp:49: error: ‘SAFE_new’ was not declared in this scope
xxx.cpp:49: error: expected ‘,’ or ‘;’ before ‘int’

这是怎么莫名其妙的错误呢?