Windows 下的内存泄漏检测方法

在 Windows 下,可使用 Visual C++ 的 C Runtime Library(CRT) 检测内存泄漏。

首先,我们在.c或.cpp 文件首行插入这一段代码:

#define _CRTDBG_MAP_ALLOC
#include <crtdbg.h>

main() 中插入如下的代码:


int main() {
        //开始的地方插入该语句
	_CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF);
	//_CrtSetBreakAlloc(79);

	//其它代码

        //return前插入该语句
	_CrtDumpMemoryLeaks();
	return 0;
}

Visual Studio的Output的输出如下:

C:\Temp\memleak\memleak.cpp(15) : {79} normal block at 0x00441BA0, 2 bytes long.

Data: <AB> 41 42

Object dump complete.

我们可以加上 _CrtSetBreakAlloc(79); 来调试,那么它便会在第 79 次时中断于分配调用的位置,那时候就能从调用堆栈去找出来龙去脉。

posted @ 2018-05-12 17:20  ,,,沙子,,,  阅读(377)  评论(0编辑  收藏  举报