_CrtDumpMemoryLeaks報告程式中的記憶體泄露問題(簡單範例程式碼) #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; }
#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 plain copy print ? Detected memory leaks!<BR> Dumping objects -><BR> f:\myprojects\windows\chapter3_2\chapter3_2.cpp(21) : {116} normal block at 0x00407378, 40 bytes long.<BR> Data: < > CD CD CD CD CD CD CD CD CD CD CD CD CD CD CD CD <BR> 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調試的時候就會自動斷在出現記憶體泄露的地方,這樣就可以很容易的找到存在問題的語句.但是要求必須是可重新進入的,在多線程情況下,可能這個數值不固定。