1. 使能內存泄漏檢測
#define _CRTDBG_MAP_ALLOC
#include <stdlib.h>
#include <crtdbg.h>
注1:語句順序不能修改;
注2:僅對DEBUG版本有效
注3:#define語句能夠去掉,但leak dump會丟失細節信息,如:泄漏的代碼文件及行號
2. 打印泄漏內存報告
在合適的地方調用下面的語句,便可看到內存泄漏報告:
_CrtDumpMemoryLeaks();
3. 若是應用程序有多個出口,可 以經過設置調試標誌自動在程序退出時打印內存泄漏信息,而不是手動在每一個出口添加:
_CrtSetDbgFlag ( _CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF );
4. 默認情 況下報告打印在VS的Debug面板的Output窗口,該行爲能夠經過下面的API進行修改:
_CrtSetReportMode( _CRT_ERROR, _CRTDBG_MODE_DEBUG );
CRT內存泄漏報告解讀。。
若是定義了_CRTDBG_MAP_ALLOC宏,報告會是這樣:
Detected memory leaks!
Dumping objects ->
C:\PROGRAM FILES\VISUAL STUDIO\MyProjects\leaktest\leaktest.cpp(20) : {18}
normal block at 0x00780E80, 64 bytes long.
Data: < > CD CD CD CD CD CD CD CD CD CD CD CD CD CD CD CD
Object dump complete.
若是沒有定義,則是這樣:
Detected memory leaks!
Dumping objects ->
{18} normal block at 0x00780E80, 64 bytes long.
Data: < > CD CD CD CD CD CD CD CD CD CD CD CD CD CD CD CD
Object dump complete.
解讀:
內存塊號,這裏是18;
內存塊類型:這裏是normal;
泄漏的內存地址:這裏是0x00780E80;
泄漏的內存塊大小,這裏是64bytes;
泄漏內存的前16byte的十六進制值;
CRT內存類型有5種:
normal:應用程序本身開闢的內存塊
client:MFC對象特有的類型
crt:crt本身使用的內存塊
free:已經被釋放的(不會出如今報告中)
ignore:應用程序顯示標誌爲排除在內存泄漏報告中的內存塊
CRT經過改寫new和malloc來實現內存泄漏監視:
#ifdef _DEBUG
#ifndef DBG_NEW
#define DBG_NEW new ( _NORMAL_BLOCK , __FILE__ , __LINE__ )
#define new DBG_NEW
#endif
#endif // _DEBUG
設置內存開闢斷點:
1.在監視窗口修改crt全局變量:_crtBreakAlloc,
若是使用/MD編譯選項,需加上上下文操做符: {,,ucrtbased.dll}_crtBreakAlloc,若是使用/MD編譯選項,需加上上下文操做符:
2. 經過CRT API設置 _CrtSetBreakAlloc(xx);
手動比較內存:
典型用法:
_CrtMemState s1;
_CrtMemCheckpoint( &s1 );
// memory allocations take place here
_CrtMemState s2;
_CrtMemCheckpoint( &s2 );
_CrtMemState s3;
if ( _CrtMemDifference( &s3, &s1, &s2) )
_CrtMemDumpStatistics( &s3 );
調試