mtrace分析内存泄漏


1. 测试程序

#include 
#include <string.h>
#include 
#include 
#include 

static void memory_leak_test()
{
    char *p = malloc(4 * 1024);
    free(p);
    p = malloc(2 * 1024);
    p = malloc(1 * 1024);
}

static int check_leak_start(void)
{
   char log_path[64] = "./log";
   setenv("MALLOC_TRACE", log_path, 1); //设置log保存路径
   mtrace();

   return 0;
}

static int check_leak_end(void)
{
   char log_path[64] = "./log";
   setenv("MALLOC_TRACE", log_path, 1); //设置log保存路径
   mtrace();

   return 0;
}

void main()
{
    check_leak_start();
    memory_leak_test();
    check_leak_end();
}

实验结果:

~/tmp/mtrace_test$ gcc -g mtrace_test.c -o pp
~/tmp/mtrace_test$ ./pp
~/tmp/mtrace_test$ cat log 
= Start
@ ./pp:[0x400678] + 0x1609560 0x1000
@ ./pp:[0x400688] - 0x1609560
@ ./pp:[0x400692] + 0x1609560 0x800
@ ./pp:[0x4006a0] + 0x1609d70 0x400
~/tmp/mtrace_test$ 
~/tmp/mtrace_test$ addr2line -f -e pp 0x400678
memory_leak_test
.../tmp/mtrace_test/mtrace_test.c:10
~/tmp/mtrace_test$ 
~/tmp/mtrace_test$ addr2line -f -e pp 0x400688
memory_leak_test
.../tmp/mtrace_test/mtrace_test.c:12 //应该是11行的,有点错位
~/tmp/mtrace_test$
~/tmp/mtrace_test$ addr2line -f -e pp 0x400692
memory_leak_test
.../tmp/mtrace_test/mtrace_test.c:12
~/tmp/mtrace_test$
~/tmp/mtrace_test$ addr2line -f -e pp 0x4006a0
memory_leak_test
.../tmp/mtrace_test/mtrace_test.c:13

总结

只是打印出申请和释放内存的位置。

参考:https://zhuanlan.zhihu.com/p/83547768