C++中基于Crt的内存泄露检测(二)

2014-11-24 07:47:23 · 作者: · 浏览: 1
)malloc(10);
char d;
char* p1 = new(&d) char('a');
return 0;
}
(6)因为STL里map内的tree用到了placement new, 所以如果你这样用会编译失败:
#ifdef _DEBUG
#define DEBUG_CLIENTBLOCK new( _CLIENT_BLOCK, __FILE__, __LINE__)
#else
#define DEBUG_CLIENTBLOCK
#endif
#define _CRTDBG_MAP_ALLOC
#include
#ifdef _DEBUG
#define new DEBUG_CLIENTBLOCK
#endif
#include
你应该把 #include 放到 宏定义的前面。
(7) 如果你在宏 #define new DEBUG_CLIENTBLOCK 之后再声明或定义 operator new函数, 都会因为宏替代而编译失败。
而STL的xdebug文件恰恰申明了operator new函数, 所以请确保new的替代宏放在所有include头文件的最后, 尤其要放在STL头文件的后面。
//MyClass.cpp
#include "myclass.h"
#include
#include
#ifdef _DEBUG
#define new DEBUG_CLIENTBLOCK
#endif
MyClass::MyClass()
{
char* p = new char('a');
}
(8)如果你觉得上面的这种new替代宏分散在各个CPP里太麻烦, 想把所有的东西放到一个通用头文件里,请参考下面定义的方式:
//MemLeakChecker.h
#include
#include
//other STL file
#ifdef _DEBUG
#define DEBUG_CLIENTBLOCK new( _CLIENT_BLOCK, __FILE__, __LINE__)
#else
#define DEBUG_CLIENTBLOCK
#endif
#define _CRTDBG_MAP_ALLOC
#include
#ifdef _DEBUG
#define new DEBUG_CLIENTBLOCK
#endif
(9)简单判断某个独立函数有没有内存泄露可以用下面的方法:
class DbgMemLeak
{
_CrtMemState m_checkpoint;
public:
explicit DbgMemLeak()
{
_CrtMemCheckpoint(&m_checkpoint);
};
~DbgMemLeak()
{
_CrtMemState checkpoint;
_CrtMemCheckpoint(&checkpoint);
_CrtMemState diff;
_CrtMemDifference(&diff, &m_checkpoint, &checkpoint);
_CrtMemDumpStatistics(&diff);
_CrtMemDumpAllObjectsSince(&diff);
};
};
int _tmain(int argc, _TCHAR* argv[])
{
DbgMemLeak check;
{www.2cto.com
char* p = new char();
char* pp = new char[10];
char* ppp = (char*)malloc(10);
}
return 0;
}
(10) 其实知道了原理, 自己写一套C++内存泄露检测也不难, 主要是重载operator new和operator delete, 可以把每次内存分配情况都记录在一个Map里, delete时删除记录, 最后程序退出时把map里没有delete的打印出来。 当然我们知道Crt在实现new时一般实际上调的是malloc, 而malloc可能又是调HeapAlloc,而HeapAlloc可能又是调用RtlAllocateHeap, 所以理论上我们可以在这些函数的任意一层拦截和记录。但是如果你要实现自己的跨平台内存泄露检测,还是重载operator new吧。