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

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

#include "stdafx.h"   
  1. #include <Windows.h>   
  2. #include <crtdbg.h>    
  3.   
  4. #ifdef _DEBUG //这个要加上,否则不会输出定义到那个文件中(及不包含存在内存泄露的该cpp文件的相关信息)   
  5.     #define new  new(_NORMAL_BLOCK, __FILE__, __LINE__)   
  6. #endif   
  7.   
  8. int _tmain(int argc, _TCHAR* argv[])  
  9. {  
  10.     _CrtSetDbgFlag(_CRTDBG_LEAK_CHECK_DF | _CrtSetDbgFlag(_CRTDBG_REPORT_FLAG));  
  11.   
  12.     _CrtDumpMemoryLeaks();  
  13.     //_CrtSetBreakAlloc(116);   
  14.     //_CrtMemState s1, s2, s3;   
  15.     //_CrtMemCheckpoint(&s1);   
  16.   
  17.     int* pInt = new int[10];  
  18.     //_CrtMemCheckpoint(&s2);   
  19.   
  20.     //if(_CrtMemDifference(&s3, &s1, &s2))   
  21.     //{   
  22.     //  _CrtMemDumpStatistics(&s3);   
  23.     //}   
  24.     return 0;  
  25. }  
#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窗口就会输出相关的内存泄露的信息(如果存在的话),类似这样的信息
  1. Detected memory leaks!<BR>  
  2. Dumping objects -><BR>  
  3. f:\myprojects\windows\chapter3_2\chapter3_2.cpp(21) : {116} normal block at 0x00407378, 40 bytes long.<BR>  
  4.  Data: <                > CD CD CD CD CD CD CD CD CD CD CD CD CD CD CD CD <BR>  
  5. Object dump complete.<BR>  
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调试的时候就会自动断在出现内存泄露的地方,这样就可以很容易的找到存在问题的语句.但是要求必须是可重入的,在多线程情况下,可能这个数值不固定。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值