所有使用動態記憶體分配(dynamic memory allocation)的程式都有機會遇上記憶體洩露(memory leakage)問題,在linux裡有三種常用工具來檢測記憶體洩露的情況,包括:
mtrace
dmalloc
memwatch
mtrace是三款工具之中是最簡單易用的,mtrace是乙個c函式,在裡宣告及定義,函式原型為:
void mtrace(void);
其實mtrace是類似malloc_hook的 malloc handler,只不過mtrace的handler function已由系統為你寫好,但既然如此,系統又怎麼知道你想將malloc/free的記錄寫在**呢?為此,呼叫mtrace()前要先設定 malloc_trace環境變數:
#include
....
setenv("malloc_trace", "output_file_name", 1);
...「output_file_name」就是儲存檢測結果的檔案的名稱。
但是檢測結果的格式是一般人無法理解的,而只要有安裝mtrace的話,就會有一名為mtrace的perl script,在shell輸入以下指令:
mtrace [binary] output_file_name
就會將output_file_name的內容轉化成能被理解的語句,例如「no memory leaks」,「0x12345678 free 10 was never alloc」諸如此類。
例如以下有一函式:(暫且放下single entry single exit的原則)
#include
#include
#include
#include
int main()
return 0; }
執行後,再用mtrace 將結果輸出:
- 0x08049670 free 3 was never alloc'd 0x42029acc
- 0x080496f0 free 4 was never alloc'd 0x420dc9e9
- 0x08049708 free 5 was never alloc'd 0x420dc9f1
- 0x08049628 free 6 was never alloc'd 0x42113a22
- 0x08049640 free 7 was never alloc'd 0x42113a52
- 0x08049658 free 8 was never alloc'd 0x42113a96
memory not freed:
-----------------
address size caller
0x08049a90 0x1 at 0x80483fe
最後一行標明有乙個大小為1 byte的記憶體尚未釋放,大概是指「hello」吧。
若我們把該段記憶體釋放:
#include
#include
#include
#include
int main()
free(hello);
return 0; }
結果如下:
- 0x080496b0 free 4 was never alloc'd 0x42029acc
- 0x08049730 free 5 was never alloc'd 0x420dc9e9
- 0x08049748 free 6 was never alloc'd 0x420dc9f1
- 0x08049668 free 7 was never alloc'd 0x42113a22
- 0x08049680 free 8 was never alloc'd 0x42113a52
- 0x08049698 free 9 was never alloc'd 0x42113a96
no memory leaks.
mtrace的原理是記錄每一對malloc-free的執行,若每乙個malloc都有相應的free,則代表沒有記憶體洩露,對於任何非malloc/free情況下所發生的記憶體洩露問題,mtrace並不能找出來。
Linux C記憶體洩露檢測工具
在linux下些c語言程式,最大的問題就是沒有乙個好的程式設計ide,當然想kdevelop等工具都相當的強大,但我還是習慣使用kdevelop工具,由於沒有乙個習慣的程式設計ide,記憶體檢測也就成了在linux下編寫程式的乙個大問題。是不是說沒有一種記憶體檢查工具能夠在linux使用呢,也不是,...
記憶體洩露檢測
c 中檢測記憶體洩漏可以引入系統定義的巨集來檢視,內存在哪個位置洩漏 檔案開始處加入下列定義 define crtdbg map alloc include include 程式退出時加入以下函式 crtdumpmemoryleaks 如果有洩漏會顯示 記憶體洩漏是程式設計中常常見到的乙個問題,我所...
檢測記憶體洩露
程式結束時,作業系統會 程式占用的資源.但是,只要程式還在執行,如果不進行清理,資源最終可能被耗盡.1.vc記憶體洩露檢查工具 visual leak detector 現在已知的最新有2.0版本的,使方法不詳。使用 visual leak detector 2.2.3 在vs工程的linker i...