西西軟件園多重安全檢測(cè)下載網(wǎng)站、值得信賴的軟件下載站!
軟件
軟件
文章
搜索

首頁(yè)編程開發(fā)VC|VC++ → C++中運(yùn)用Crt 的內(nèi)存調(diào)試功能檢測(cè)內(nèi)存泄露

C++中運(yùn)用Crt 的內(nèi)存調(diào)試功能檢測(cè)內(nèi)存泄露

相關(guān)文章發(fā)表評(píng)論 來源:西西整理時(shí)間:2013/2/26 8:40:13字體大�。�A-A+

作者:西西點(diǎn)擊:67次評(píng)論:0次標(biāo)簽: vc

vcc隱生宙交易所v1.0.15 安卓版
  • 類型:金融理財(cái)大�。�23.6M語(yǔ)言:中文 評(píng)分:10.0
  • 標(biāo)簽:
立即下載

盡管這個(gè)概念已經(jīng)讓人說濫了 ,還是想簡(jiǎn)單記錄一下, 以備以后查詢。

#ifdef _DEBUG
#define DEBUG_CLIENTBLOCK   new( _CLIENT_BLOCK, __FILE__, __LINE__)
#else
#define DEBUG_CLIENTBLOCK
#endif
#define _CRTDBG_MAP_ALLOC
#include 
#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;
}


主要原理是運(yùn)用Crt 的內(nèi)存調(diào)試功能, 通過宏替代默認(rèn)的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會(huì)把此次分配內(nèi)存的文件名和行號(hào)以及大小等記錄下來,最后當(dāng)調(diào)用用_CrtDumpMemoryLeaks(); 時(shí)如果還沒釋放就會(huì)打印出來。
結(jié)果如下:

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.


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

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

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)如果程序有多個(gè)出口或是有涉及到全局變量, 可以通過_CrtSetDbgFlag 設(shè)置標(biāo)志讓程序退出時(shí)自動(dòng)打印泄露 , 比如
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的替代宏放到每個(gè)Cpp里而不是放到一個(gè)通用的頭文件中, 實(shí)際上MFC也是這么做的
#ifdef _DEBUG
#define new DEBUG_CLIENTBLOCK
#endif

(5)上面的operator new只能照顧到最普通的new, 實(shí)際上operator new是有任意多種重載方式, 只需要確保第一個(gè)參數(shù)是表示大小。 比如下面的placement new就會(huì)編譯失敗, 因?yàn)楹晏娲蟾袷讲环弦罅耍?所以如果你的CPP用了非標(biāo)準(zhǔn)的new, 就不要加入new的檢測(cè)宏了。
#include 

#ifdef _DEBUG
#define DEBUG_CLIENTBLOCK   new( _CLIENT_BLOCK, __FILE__, __LINE__)
#else
#define DEBUG_CLIENTBLOCK
#endif
#define _CRTDBG_MAP_ALLOC
#include 
#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)因?yàn)镾TL里map內(nèi)的tree用到了placement new,  所以如果你這樣用會(huì)編譯失敗:
#ifdef _DEBUG
#define DEBUG_CLIENTBLOCK   new( _CLIENT_BLOCK, __FILE__, __LINE__)
#else
#define DEBUG_CLIENTBLOCK
#endif
#define _CRTDBG_MAP_ALLOC
#include 
#ifdef _DEBUG
#define new DEBUG_CLIENTBLOCK
#endif

#include 

你應(yīng)該把 #include 放到 宏定義的前面。

(7) 如果你在宏 #define new DEBUG_CLIENTBLOCK 之后再聲明或定義 operator new函數(shù), 都會(huì)因?yàn)楹晏娲幾g失敗。
而STL的xdebug文件恰恰申明了operator new函數(shù), 所以請(qǐng)確保new的替代宏放在所有include頭文件的最后, 尤其要放在STL頭文件的后面。

//MyClass.cpp

#include "myclass.h"
#include 
#include 

#ifdef _DEBUG
#define new DEBUG_CLIENTBLOCK
#endif

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

(8)如果你覺得上面的這種new替代宏分散在各個(gè)CPP里太麻煩, 想把所有的東西放到一個(gè)通用頭文件里,請(qǐng)參考下面定義的方式:
//MemLeakChecker.h 
#include 
#include 
//other STL file

#ifdef _DEBUG
#define DEBUG_CLIENTBLOCK   new( _CLIENT_BLOCK, __FILE__, __LINE__)
#else
#define DEBUG_CLIENTBLOCK
#endif
#define _CRTDBG_MAP_ALLOC
#include 
#ifdef _DEBUG
#define new DEBUG_CLIENTBLOCK
#endif

 (9)簡(jiǎn)單判斷某個(gè)獨(dú)立函數(shù)有沒有內(nèi)存泄露可以用下面的方法:
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;
}

    數(shù)字貨幣交易平臺(tái)
    (201)數(shù)字貨幣交易平臺(tái)
    數(shù)字貨幣交易平臺(tái)app是針對(duì)全球數(shù)字貨幣市場(chǎng)推出的交易所軟件。數(shù)字貨幣交易平臺(tái)能夠?qū)崟r(shí)跟蹤全球范圍內(nèi)的數(shù)字貨幣交易數(shù)據(jù)信息,幫助相關(guān)的行業(yè)人員快速掌握最新的數(shù)字貨幣市場(chǎng)走勢(shì),讓您能輕松作出決策。本次為大家整合了大量的數(shù)字貨幣交易平臺(tái)app資源,基本上都具備了全部的數(shù)據(jù)查詢功能,想要入駐數(shù)字貨幣市場(chǎng)的朋友們最好挑選一款使用哦~數(shù)字貨幣交易平臺(tái)相關(guān)特點(diǎn):交易成本低與傳統(tǒng)的銀行轉(zhuǎn)賬、匯款等方式相比,數(shù)字貨幣交易...更多>>
    • 火幣全球站v5.3.0 安卓版

      08-19 / 32.2M

      推薦理由:火幣全球站,全球化的數(shù)字貨幣交易平臺(tái)軟件,擁有最安全的比特幣交易平臺(tái)服務(wù),為您整合包含比特幣,萊特幣
    • Bittrex(B網(wǎng)助手)v1.2 安卓版

      08-19 / 2.7M

      推薦理由:Bittrex(B網(wǎng)助手),全新的BittrexB網(wǎng)交易平臺(tái),為您呈現(xiàn)最經(jīng)典的數(shù)字交易所平臺(tái),Bittrexapp整合B網(wǎng)全部交易
    • 華夏交易所app1.0.1安卓版

      08-19 / 5.0M

      推薦理由:華夏交易所app是中國(guó)華夏文化產(chǎn)權(quán)交易中心針對(duì)投資者開發(fā)的移動(dòng)手機(jī)應(yīng)用,用戶可以使用這款軟件輕松地查看最
    • mg交易所v2.0.4 安卓版

      08-19 / 16.8M

      推薦理由:mgex交易所app權(quán)威的區(qū)塊鏈為廣大用戶精心打造的手機(jī)交易資訊應(yīng)用平臺(tái),用戶通過mgex交易所在交易中,能夠?yàn)?/em>
    • ZB網(wǎng)交易平臺(tái)appv1.5.4 安卓版

      08-19 / 18.8M

      推薦理由:ZB網(wǎng)交易平臺(tái)app,ZB網(wǎng)客戶端軟件,用戶可以在手機(jī)上隨時(shí)查看全網(wǎng)的數(shù)據(jù)分析,登錄后可以查看關(guān)注的幣種走勢(shì)
    • Bitfinex交易平臺(tái)v2.3.6 安卓版

      08-19 / 15.6M

      推薦理由:Bitfinex交易平臺(tái),Bitfinex比特幣數(shù)字交易所平臺(tái),匯集了全球范圍內(nèi)的比特幣交易市場(chǎng)數(shù)據(jù),用戶可以輕松點(diǎn)

    相關(guān)評(píng)論

    閱讀本文后您有什么感想? 已有人給出評(píng)價(jià)!

    • 8 喜歡喜歡
    • 3 頂
    • 1 難過難過
    • 5 囧
    • 3 圍觀圍觀
    • 2 無聊無聊

    熱門評(píng)論

    最新評(píng)論

    發(fā)表評(píng)論 查看所有評(píng)論(0)

    昵稱:
    表情: 高興 可 汗 我不要 害羞 好 下下下 送花 屎 親親
    字?jǐn)?shù): 0/500 (您的評(píng)論需要經(jīng)過審核才能顯示)