C 無 GC,malloc 後忘 free 導致洩漏。GNU C 庫提供 mtrace/muntrace 追蹤工具。
export MALLOC_TRACE=/path/to/trace.log
#include <mcheck.h>
#include <stdlib.h>
int main() {
mtrace(); // 安裝 malloc/realloc/free 追蹤鉤子
int *p = malloc(sizeof(int));
// 故意不 free
return 0; // 程序結束自動調用 muntrace(不建議手動調用,影響庫內部追蹤)
}
-DDEBUG 條件編譯或直接鏈接)。mtrace 命令轉換:
mtrace ./a.out /path/to/trace.log
Memory not freed: ---------------------------- Address Size Caller 0x092a6378 0x4 at /root/tmp.c:9
明確指出第 9 行 malloc 未配對 free。
mtrace 會追蹤整個進程(含 C 庫內部分配),輸出可能較多。muntrace(),以免過早卸載鉤子漏報後續洩漏。-fsanitize=address) 綜合檢測。