尽管这个概念已经让人说滥了 ,还是想简单记录一下, 以备以后查询。
#ifdef _DEBUG
_CrtDumpMemoryLeaks(); return 0; |
主要原理是运用Crt 的内存调试功能,通过宏替代默认的operator new,让它被下面版本替代:
void *__CRTDECL operator new( RTCCALLBACK(_RTC_Allocate_hook, (res, cb, 0)); /* if the allocation fails, we throw std::bad_alloc */ return res; |
这样Crt会把此次分配内存的文件名和行号以及大小等记录下来,最后当调用用_CrtDumpMemoryLeaks();时如果还没释放就会打印出来。
结果如下:
Detected memory leaks! Dumping objects -> f:\test\memleakchecker\memleakchecker\memleakchecker.cpp(23) : {108} normal block at 0x0003A1A8, 10 bytes long. Data: < > CD CD CD CD CD CD CD CD CD CD f:\test\memleakchecker\memleakchecker\memleakchecker.cpp(22) : {107} client block at 0x0003A160, subtype 0, 10 bytes long. Data: < > CD CD CD CD CD CD CD CD CD CD f:\test\memleakchecker\memleakchecker\memleakchecker.cpp(21) : {106} client block at 0x0003A120, subtype 0, 1 bytes long. Data: < > 00 Object dump complete. |