C++中關於Crt的記憶體流失檢測的分析介紹

來源:互聯網
上載者:User

儘管這個概念已經讓人說濫了 ,還是想簡單記錄一下, 以備以後查詢。

複製代碼 代碼如下:#ifdef _DEBUG
#define DEBUG_CLIENTBLOCK new( _CLIENT_BLOCK, __FILE__, __LINE__)
#else
#define DEBUG_CLIENTBLOCK
#endif
#define _CRTDBG_MAP_ALLOC
#include <crtdbg.h>
#ifdef _DEBUG
#define new DEBUG_CLIENTBLOCK
#endif

int _tmain(int argc, _TCHAR* argv[])
{
char* p = new char();
char* pp = new char[10];
char* ppp = (char*)malloc(10);

_CrtDumpMemoryLeaks();

return 0;
}

主要原理是運用Crt 的記憶體調試功能, 通過宏替代預設的operator new, 讓它被下面版本替代:複製代碼 代碼如下:void *__CRTDECL operator new(
size_t cb,
int nBlockUse,
const char * szFileName,
int nLine
)
_THROW1(_STD bad_alloc)
{
/* _nh_malloc_dbg already calls _heap_alloc_dbg in a loop and calls _callnewh
if the allocation fails. If _callnewh returns (very likely because no
new handlers have been installed by the user), _nh_malloc_dbg returns NULL.
*/
void *res = _nh_malloc_dbg( cb, 1, nBlockUse, szFileName, nLine );

RTCCALLBACK(_RTC_Allocate_hook, (res, cb, 0));

/* if the allocation fails, we throw std::bad_alloc */
if (res == 0)
{
static const std::bad_alloc nomem;
_RAISE(nomem);
}

return res;
}

這樣Crt會把此次分配記憶體的檔案名稱和行號以及大小等記錄下來,最後當調用用_CrtDumpMemoryLeaks(); 時如果還沒釋放就會列印出來。
結果如下:複製代碼 代碼如下:Detected memory leaks!
Dumping objects ->
f:\test\memleakchecker\memleakchecker\memleakchecker.cpp(23) : {108} normal block at 0x0003A1A8, 10 bytes long.
Data: < > CD CD CD CD CD CD CD CD CD CD
f:\test\memleakchecker\memleakchecker\memleakchecker.cpp(22) : {107} client block at 0x0003A160, subtype 0, 10 bytes long.
Data: < > CD CD CD CD CD CD CD CD CD CD
f:\test\memleakchecker\memleakchecker\memleakchecker.cpp(21) : {106} client block at 0x0003A120, subtype 0, 1 bytes long.
Data: < > 00
Object dump complete.

下面是一些注意事項:
(1) #define _CRTDBG_MAP_ALLOC 的作用
如果不定義這個宏, C方式的malloc泄露不會被記錄下來。

(2)數字{108} {107}的作用
表示第幾次分配, 你可以通過_CrtSetBreakAlloc程式運行到預定次數時暫停 ,比如

複製代碼 代碼如下:int _tmain(int argc, _TCHAR* argv[])
{
_CrtSetBreakAlloc(108);

char* p = new char();
char* pp = new char[10];
char* ppp = (char*)malloc(10);

_CrtDumpMemoryLeaks();

return 0;
}

(3)如果程式有多個出口或是有涉及到全域變數, 可以通過_CrtSetDbgFlag 設定標誌讓程式退出時自動列印泄露 , 比如複製代碼 代碼如下:int _tmain(int argc, _TCHAR* argv[])
{
_CrtSetDbgFlag ( _CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF );

char* p = new char();
char* pp = new char[10];
char* ppp = (char*)malloc(10);

return 0;
}

(4)我們知道宏替代是最粗暴的方式, 所以盡量把下面new的替代宏放到每個Cpp裡而不是放到一個通用的標頭檔中, 實際上MFC也是這麼做的複製代碼 代碼如下:#ifdef _DEBUG
#define new DEBUG_CLIENTBLOCK
#endif

(5)上面的operator new只能照顧到最普通的new, 實際上operator new是有任意多種重載方式, 只需要確保第一個參數是表示大小。 比如下面的placement new就會編譯失敗, 因為宏替代後格式不符合要求了, 所以如果你的CPP用了非標準的new, 就不要加入new的檢測宏了。複製代碼 代碼如下:#include <new>

#ifdef _DEBUG
#define DEBUG_CLIENTBLOCK new( _CLIENT_BLOCK, __FILE__, __LINE__)
#else
#define DEBUG_CLIENTBLOCK
#endif
#define _CRTDBG_MAP_ALLOC
#include <crtdbg.h>
#ifdef _DEBUG
#define new DEBUG_CLIENTBLOCK
#endif

int _tmain(int argc, _TCHAR* argv[])
{
_CrtSetDbgFlag ( _CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF );

char* p = new char();
char* pp = new char[10];
char* ppp = (char*)malloc(10);

char d;
char* p1 = new(&d) char('a');

return 0;
}

(6)因為STL裡map內的tree用到了placement new, 所以如果你這樣用會編譯失敗:複製代碼 代碼如下:#ifdef _DEBUG
#define DEBUG_CLIENTBLOCK new( _CLIENT_BLOCK, __FILE__, __LINE__)
#else
#define DEBUG_CLIENTBLOCK
#endif
#define _CRTDBG_MAP_ALLOC
#include <crtdbg.h>
#ifdef _DEBUG
#define new DEBUG_CLIENTBLOCK
#endif

#include <map>

你應該把 #include <map>放到 宏定義的前面。

(7) 如果你在宏 #define new DEBUG_CLIENTBLOCK 之後再聲明或定義 operator new函數, 都會因為宏替代而編譯失敗。
而STL的xdebug檔案恰恰申明了operator new函數, 所以請確保new的替代宏放在所有include標頭檔的最後, 尤其要放在STL標頭檔的後面。

複製代碼 代碼如下://MyClass.cpp
#include "myclass.h"
#include <map>
#include <algorithm>

#ifdef _DEBUG
#define new DEBUG_CLIENTBLOCK
#endif

MyClass::MyClass()
{
char* p = new char('a');
}

(8)如果你覺得上面的這種new替代宏分散在各個CPP裡太麻煩, 想把所有的東西放到一個通用標頭檔裡,請參考下面定義的方式:複製代碼 代碼如下://MemLeakChecker.h
#include <map>
#include <algorithm>
//other STL file

#ifdef _DEBUG
#define DEBUG_CLIENTBLOCK new( _CLIENT_BLOCK, __FILE__, __LINE__)
#else
#define DEBUG_CLIENTBLOCK
#endif
#define _CRTDBG_MAP_ALLOC
#include <crtdbg.h>
#ifdef _DEBUG
#define new DEBUG_CLIENTBLOCK
#endif

(9)簡單判斷某個獨立函數有沒有記憶體泄露可以用下面的方法:複製代碼 代碼如下:class DbgMemLeak
{
_CrtMemState m_checkpoint;

public:
explicit DbgMemLeak()
{
_CrtMemCheckpoint(&m_checkpoint);
};

~DbgMemLeak()
{
_CrtMemState checkpoint;
_CrtMemCheckpoint(&checkpoint);
_CrtMemState diff;
_CrtMemDifference(&diff, &m_checkpoint, &checkpoint);
_CrtMemDumpStatistics(&diff);
_CrtMemDumpAllObjectsSince(&diff);
};
};

int _tmain(int argc, _TCHAR* argv[])
{
DbgMemLeak check;
{
char* p = new char();
char* pp = new char[10];
char* ppp = (char*)malloc(10);
}

return 0;
}

(10) 其實知道了原理, 自己寫一套C++記憶體泄露檢測也不難, 主要是重載operator new和operator delete, 可以把每次記憶體配置情況都記錄在一個Map裡, delete時刪除記錄, 最後程式退出時把map裡沒有delete的列印出來。 當然我們知道Crt在實現new時一般實際上調的是malloc, 而malloc可能又是調HeapAlloc,而HeapAlloc可能又是調用RtlAllocateHeap, 所以理論上我們可以在這些函數的任意一層攔截和記錄。但是如果你要實現自己的跨平台記憶體泄露檢測,還是重載operator new吧。

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.