VS2005記憶體洩露檢查

2021-05-25 00:56:14 字數 2073 閱讀 1769

記憶體洩露的含義是:拿走了一塊「堆」記憶體塊,在某檢查點處,發現沒有歸還這個記憶體塊。 如果是: 位址a = malloc(n); 因為沒有呼叫free(位址a),所以記憶體洩露了。

如果是:從使用者的記憶體池中取乙個記憶體塊,沒有呼叫相應的歸還給記憶體池的操作,也認為是「記憶體洩露」。

從**拿了乙個東西,要歸還到那個地方去。例如:從圖書館l中藉了本書,歸還給圖書館b,肯定要挨罵的。

同理,從圖書館l中藉了本**,卻還給圖書館一本雜誌,也是要挨罵的。 函式_crtdumpmemoryleaks()功能:檢查記憶體洩露並且在vc的輸出視窗列印出洩露的記憶體塊資訊。

例子1 :

#include

#include

int main()

normal block at 0x00382650, 4 bytes long. data: < > 00 00 00 00

非常好,發現了int* x對應的記憶體塊洩露了

例子2 :

template struct test

char* m_p;

test<123> t;

int main()

normal block at 0x00382708, 4 bytes long.

normal block at 0x00382650, 123 bytes long.

非常不好,它把全域性變數t也報告了。這是乙個嚴重的誤報。

原因是在_crtdumpmemoryleaks()呼叫時, 全域性變數t還沒有離開生存期呢,所以此時~test()未呼叫呢,delete m_p還沒呼叫呢。

例子3 :

test<123> t;

int main()

normal block at 0x00382708, 4 bytes long.

非常好,通過_crtsetdbgflag函式,告知crt庫在程式完全退出時,列印一下記憶體洩露的情況。

這時,全域性變數t已經析構了,所以誤報沒有了。

例子4 :

#include

using namespace std;

#define debug_new new(_normal_block, __file__, __line__)

#define new debug_new

int main()

normal block at 0x00382650, 4 bytes long.

太酷了!居然在除錯的輸出視窗中,顯示了造成記憶體洩露的**位置。

雙擊一下,還能自動跳到文字編輯器 中對應的**行上。

例子5 :

#include int main()

normal block at 0x00382708, 4 bytes long.

大括號中62就是第62次分配記憶體時,這塊記憶體洩露了。通過_crtsetbreakalloc呼叫,告知crt庫,在 第62次分配記憶體的呼叫時,

自動暫停程式,讓程式設計師檢查函式呼叫棧。 如何保證下次程式執行時,

第62此分配記憶體的呼叫就是int* x = new int;這句造成的呢?

答案是不能。

如果程式沒有複雜的時序相關的邏輯(多執行緒),輸入的值是一定的,則程式每次執行的行為是一定的。

例子8 :

class init_before_main

public: init_before_main()

{ _crtsetbreakalloc(62);

init_before_main g_tmp;

int main()

{ int* x = new int;

return 0;

這是對例子7的一點改進,保證在int* x = new int;呼叫之前,調_crtsetbreakalloc(62);。

否則,如下的呼叫順序可能會漏過了第62次分配呼叫 int* x = new int; _crtsetbreakalloc(62);

如何自己實現記憶體洩露檢查工具呢?思路很簡單,過載new,delete運算子,使用自己巨集替換malloc和free。

所有的分配和釋放動作必須經過我過手,我才能加入點私貨(統計資訊等)。這樣就可以檢查記憶體洩露了。

VS2005記憶體洩漏檢測方法

非mfc程式可以用以下方法檢測記憶體洩露 1.程式開始包含如下定義 ifdef debug define debug clientblock new client block,file line else define debug clientblock endif debug define crt...

VS2010 檢查記憶體洩露的方法

第一種 define crtdbg map alloc include include crtdumpmemoryleaks 3.output中將會跟蹤所有記憶體建立和銷毀的過程,這些資訊可以忽略。4.程式退出時,output中將會顯示出建立記憶體未釋放的 行資訊。這個可以解決絕大部分情況下出現的記...

VS2010 檢查記憶體洩露的方法

第一種 define crtdbg map alloc include include crtdumpmemoryleaks 3.output中將會跟蹤所有記憶體建立和銷毀的過程,這些資訊可以忽略。4.程式退出時,output中將會顯示出建立記憶體未釋放的 行資訊。這個可以解決絕大部分情況下出現的記...