CrtDumpMemoryLeaks報告程式中的記憶體泄露問題(簡單範例程式碼)

來源:互聯網
上載者:User
_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調試的時候就會自動斷在出現記憶體泄露的地方,這樣就可以很容易的找到存在問題的語句.但是要求必須是可重新進入的,在多線程情況下,可能這個數值不固定。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.