条件:
1. 在Debug模式下。
2.#define _CRTDBG_MAP_ALLOC
#include "stdlib.h"
#include "crtdbg.h"
_CrtDumpMemoryLeaks()可以打印出目前为止没有释放的已申请内存。
// Necessary #define _CRTDBG_MAP_ALLOC #include "stdlib.h" #include "crtdbg.h" int main() { int* p = new int(2); // Report memory leak until now. _CrtDumpMemoryLeaks(); delete p; return 0; }
上述代码输出如下:
Detected memory leaks!
Dumping objects ->
{53} normal block at 0x00394FC0, 4 bytes long.
Data: < > 02 00 00 00
Object dump complete.
其中{53}表示第53次申请的内存没有释放。
_CrtSetBreakAlloc(long n)可以在Debug时让程序自动在第n次申请内存的代码处停止。
// Necessary #define _CRTDBG_MAP_ALLOC #include "stdlib.h" #include "crtdbg.h" int main() { _CrtSetBreakAlloc(53); int* p = new int(2); // Report memory leak until now. _CrtDumpMemoryLeaks(); delete p; return 0; }
在Debug上述代码时,可以在程序停止处查看调用堆栈找到引起泄漏的内存分配代码:
当程序有多个退出点时,可以调用Using _CrtSetDbgFlag()让程序在结束时输出内存泄漏信息。
// Necessary #define _CRTDBG_MAP_ALLOC #include "stdlib.h" #include "crtdbg.h" int main() { _CrtSetDbgFlag( _CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF); int* p = new int(2); return 0; }