现在的位置: 首页 > 综合 > 正文

_CrtDumpMemoryLeaks报告程序中的内存泄露问题(简单示例代码)

2013年12月07日 ⁄ 综合 ⁄ 共 906字 ⁄ 字号 评论关闭
#include "stdafx.h"
#include <Windows.h>
#include <crtdbg.h> 

#ifdef _DEBUG //这个要加上,否则不会输出定义到那个文件中(及不包含存在内存泄露的该cpp文件的相关信息)
	#define new  new(_NORMAL_BLOCK, __FILE__, __LINE__)
#endif

int _tmain(int argc, _TCHAR* argv[])
{
	_CrtSetDbgFlag(_CRTDBG_LEAK_CHECK_DF | _CrtSetDbgFlag(_CRTDBG_REPORT_FLAG));

	_CrtDumpMemoryLeaks();
	//_CrtSetBreakAlloc(116);
	//_CrtMemState s1, s2, s3;
	//_CrtMemCheckpoint(&s1);

	int* pInt = new int[10];
	//_CrtMemCheckpoint(&s2);

	//if(_CrtMemDifference(&s3, &s1, &s2))
	//{
	//	_CrtMemDumpStatistics(&s3);
	//}
	return 0;
}

然后F5,Debug模式,在Output窗口就会输出相关的内存泄露的信息(如果存在的话),类似这样的信息

Detected memory leaks!
Dumping objects ->
f:\myprojects\windows\chapter3_2\chapter3_2.cpp(21) : {116} normal block at 0x00407378, 40 bytes long.
 Data: <                > CD CD CD CD CD CD CD CD CD CD CD CD CD CD CD CD 
Object dump complete.

注意上面这一句{116} normal block at 0x00407378中的{116};注意这里的116,如果在你的代码中打开_CrtSetBreakAlloc(116);那么F5在Debug调试的时候就会自动断在出现内存泄露的地方,这样就可以很容易的找到存在问题的语句.但是要求必须是可重入的,在多线程情况下,可能这个数值不固定。

抱歉!评论已关闭.