MFC判斷記憶體泄露的簡單方法 CmemoryState

來源:互聯網
上載者:User

MFC提供了檢查記憶體的類CmemoryState,我們就利用這個類的對象來檢查記憶體泄露,以下是具體步驟:

一:在你所檢測的程式段的開始處建立一個 CmemoryState 對象,調用其成員函數Checkpoint,以取得當前記憶體使用量情況的快照;

二:在你所檢測的程式段的末尾處再建立一個 CmemoryState 對象,調用其成員函數Checkpoint,以取得當前記憶體使用量情況的快照;

三: 再建立第三個 CmemoryState 對象,調用其成員函數Difference,把第一個CmemoryState 對象和第二個CmemeoryState 對象作為其參數,如果兩次記憶體快照不相同,則該函數返回非零,說明此程式段中有記憶體漏洞。


下面舉個簡單的例子:

CString *pstr = new CString;
int *p = new int(10);

上面new了兩次,但是都沒有delete。然後你想檢查記憶體,那麼我們就按照上面步驟所講來做。

#ifdef _DEBUG
CMemoryState oldMemState, newMemState, diffMemState;
oldMemState.Checkpoint();
#endif

CString *pstr = new CString;
int *p = new int(10);

#ifdef _DEBUG
newMemState.Checkpoint();
if( diffMemState.Difference( oldMemState, newMemState ) )
{
TRACE( "Memory leaked!\n" );
}
#endif

在調試的狀態下可以觀察diffMemState的值,iCount下可以看到new的記憶體幾個沒有delete,iSize下面可以看到申請的多少記憶體沒有釋放。

上例中,iConut下面的值為2,delete下面的值為14。

聯繫我們

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