linux C 内存泄漏查找工具mtrace使用
C语言内存管理是一个比较麻烦的问题,对于新手来说,经常会出现内存泄漏,和内存越限问题。
通过包含mtrace的相关函数调用,mtrace可以跟踪各种malloc,free,calloc, 的调用,并将调用记录存储到指定的文件中,然后通过mtrace工具即可分析是否有内存未被释放。
以下是有问题的代码
#include <stdlib.h>
int main(void) {
int * a;
a = malloc(sizeof(int));
/* allocate memory and assign it to the pointer */
return 0; /* we exited the program without freeing memory */
/* we should have released the allocated memory with the statement “free(a)” */
}
mtrace使用方法
- 设置MALLOC_TRACE环境变量,mtrace会使用该变量值作为输出文件,
MALLOC_TRACE=/home/YourUserName/path/to/program/MallocTraceOutputFile.txt
export MALLOC_TRACE; - 在main函数的源代码中包含mcheck.h
#include <mcheck.h>
- 在开始任何内存分配调用之前,调用mtrace()函数,在想结束分析的代码位置调用muntrace();
mtrace(); //memory allocation and free muntrace();
- 编译源代码,gcc -g -o a.out main.c, 运行程序,内存泄漏信息会被输出到MALLOC_TRACE指定的文件中。输出文件并非可读信息,需要使用mtrace命令解析。
- 执行mtrace命令解析MALLOC_TRACE文件,
mtrace <exec_file_name> <malloc_trace_filename> #示例: mtrace a.out MallocTraceOutputFile.txt
-
Memory not freed: ----------------- Address Size Caller 0x08049910 0x4 at /home/sureshsathiah/tips/leak.c:9
以上即可大致分析C内存泄漏问题。
参考链接: