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

来源:互联网 发布:网络推广电话营销话术 编辑:程序博客网 时间:2024/05/19 04:28

_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__)#endifint _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窗口就会输出相关的内存泄露的信息(如果存在的话),类似这样的信息
[cpp] view plaincopyprint?
  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调试的时候就会自动断在出现内存泄露的地方,这样就可以很容易的找到存在问题的语句.但是要求必须是可重入的,在多线程情况下,可能这个数值不固定。