尽管这个概念已经让人说滥了 ,还是想简单记录一下, 以备以后查询。
int _tmain(int argc, _TCHAR* argv[])
{
char* p = new char();
char* pp = new char[10];
char* ppp = (char*)malloc(10);
_CrtDumpMemoryLeaks();
return 0;
}
</div>
主要原理是运用Crt 的内存调试功能, 通过宏替代默认的operator new, 让它被下面版本替代:
RTCCALLBACK(_RTC_Allocate_hook, (res, cb, 0));
/* if the allocation fails, we throw std::bad_alloc */
if (res == 0)
{
static const std::bad_alloc nomem;
_RAISE(nomem);
}
return res;
}
</div>
这样Crt会把此次分配内存的文件名和行号以及大小等记录下来,最后当调用用_CrtDumpMemoryLeaks(); 时如果还没释放就会打印出来。
结果如下:
(2)数字{108} {107}的作用
表示第几次分配, 你可以通过_CrtSetBreakAlloc程序运行到预定次数时暂停 ,比如
char* p = new char();
char* pp = new char[10];
char* ppp = (char*)malloc(10);
_CrtDumpMemoryLeaks();
return 0;
}
</div>
(3)如果程序有多个出口或是有涉及到全局变量, 可以通过_CrtSetDbgFlag 设置标志让程序退出时自动打印泄露 , 比如
char* p = new char();
char* pp = new char[10];
char* ppp = (char*)malloc(10);
return 0;
}
</div>
(4)我们知道宏替代是最粗暴的方式, 所以尽量把下面new的替代宏放到每个Cpp里而不是放到一个通用的头文件中, 实际上MFC也是这么做的
#ifdef _DEBUG
#define DEBUG_CLIENTBLOCK new( _CLIENT_BLOCK, __FILE__, __LINE__)
#else
#define DEBUG_CLIENTBLOCK
#endif
#define _CRTDBG_MAP_ALLOC
#include <crtdbg.h>
#ifdef _DEBUG
#define new DEBUG_CLIENTBLOCK
#endif
int _tmain(int argc, _TCHAR* argv[])
{
_CrtSetDbgFlag ( _CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF );
char* p = new char();
char* pp = new char[10];
char* ppp = (char*)malloc(10);
char d;
char* p1 = new(&d) char('a');
return 0;
}
</div>
(6)因为STL里map内的tree用到了placement new, 所以如果你这样用会编译失败:
#include <map>
</div>
你应该把 #include <map>放到 宏定义的前面。
(7) 如果你在宏 #define new DEBUG_CLIENTBLOCK 之后再声明或定义 operator new函数, 都会因为宏替代而编译失败。
而STL的xdebug文件恰恰申明了operator new函数, 所以请确保new的替代宏放在所有include头文件的最后, 尤其要放在STL头文件的后面。
#ifdef _DEBUG
#define new DEBUG_CLIENTBLOCK
#endif
MyClass::MyClass()
{
char* p = new char('a');
}