您的位置:首页 > 其它

利用CRT库函数检查内存泄漏

2011-08-24 20:57 169 查看
条件:

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" intmain() { int*p=newint(2); //Reportmemoryleakuntilnow. _CrtDumpMemoryLeaks(); deletep; return0; }

上述代码输出如下:

Detectedmemoryleaks!
Dumpingobjects->
{53}normalblockat0x00394FC0,4byteslong.
Data:<>02000000
Objectdumpcomplete.

其中{53}表示第53次申请的内存没有释放。

_CrtSetBreakAlloc(longn)可以在Debug时让程序自动在第n次申请内存的代码处停止。

//Necessary #define_CRTDBG_MAP_ALLOC #include"stdlib.h" #include"crtdbg.h" intmain() { _CrtSetBreakAlloc(53); int*p=newint(2); //Reportmemoryleakuntilnow. _CrtDumpMemoryLeaks(); deletep; return0; }

在Debug上述代码时,可以在程序停止处查看调用堆栈找到引起泄漏的内存分配代码:





当程序有多个退出点时,可以调用Using_CrtSetDbgFlag()让程序在结束时输出内存泄漏信息。

//Necessary #define_CRTDBG_MAP_ALLOC #include"stdlib.h" #include"crtdbg.h" intmain() { _CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF|_CRTDBG_LEAK_CHECK_DF); int*p=newint(2); return0; }
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: