針對指標操作複雜程式的記憶體溢出/洩漏難題,Linux 提供 mtrace(依賴 glibc),追蹤記憶體分配/釋放操作,快速定位錯誤。
<mcheck.h>,main() 開頭呼叫 mtrace(),後續所有 malloc/free 自動記錄export MALLOC_TRACE=mymemory.log 指定日誌輸出路徑mtrace 程式名 $MALLOC_TRACE 輸出未釋放記憶體區塊(位址、大小、呼叫來源)無 export 或環境變數機制時,使用 glibc putenv() 將變數寫入程式:
int putenv(char *string);
無正常終止場景(如守護進程),在需分析處呼叫 muntrace() 立即產生日誌,隨後用 mtrace 分析。
[hwang@langchao test]$ cat testmtrace.c
#include <stdio.h>
#include <stdlib.h>
#include <mcheck.h>
int main() {
char *hello;
mtrace();
hello = (char*) malloc(20);
sprintf(hello, "hello world!");
return 0; // 故意不 free 造成洩漏
}
[hwang@langchao test]$ export MALLOC_TRACE=mytrace.log
[hwang@langchao test]$ gcc testmtrace.c -o testmtrace
[hwang@langchao test]$ ./testmtrace
[hwang@langchao test]$ mtrace testmtrace mytrace.log
Memory not freed:
-----------------
Address Size Caller
0x08049860 0x14 at /usr/src/build/.../glibc-2.2.4/csu/init.c:0
輸出列出所有未釋放記憶體區塊:位址、大小、呼叫來源,方便快速定位問題。