linux——内存泄露检测工具

  • Post author:
  • Post category:linux


文章目录

内存泄漏检查工具

测试代码(包含mtrace部分):

$ cat test.c
#include <stdio.h>
#include <malloc.h>
#include <mcheck.h>

int main() {
        mtrace();
        int *n = (int*)malloc(sizeof(int) * 4);
        muntrace();
        return 0;
}

编译:

#必须添加-g参数,不然无法确认是在哪个文件的第几行出现问题
$ gcc -g -o test test.c

Valgrind

可以检测数组越界、内存无效读取,内存泄漏

官网:

https://www.valgrind.org/


下载地址:

https://www.valgrind.org/downloads

#下载安装,当前最新版本3.18.1
curl -O https://sourceware.org/pub/valgrind/valgrind-3.18.1.tar.bz2
tar jvxf valgrind-3.18.1.tar.bz2
cd valgrind-3.18.1
./configue --prefix=`pwd`/build
make -j8
make install

#在结果中可看到test.c:7行存在内存泄漏
#其他情况可根据具体打印信息判断是否存在问题
$ valgrind --leak-check=full ./test
==20799== Memcheck, a memory error detector
==20799== Copyright (C) 2002-2017, and GNU GPL'd, by Julian Seward et al.
==20799== Using Valgrind-3.15.0 and LibVEX; rerun with -h for copyright info
==20799== Command: ./test
==20799==
==20799==
==20799== HEAP SUMMARY:
==20799==     in use at exit: 16 bytes in 1 blocks
==20799==   total heap usage: 1 allocs, 0 frees, 16 bytes allocated
==20799==
==20799== 16 bytes in 1 blocks are definitely lost in loss record 1 of 1
==20799==    at 0x4C29F73: malloc (vg_replace_malloc.c:309)
==20799==    by 0x4005E3: main (test.c:7)
==20799==
==20799== LEAK SUMMARY:
==20799==    definitely lost: 16 bytes in 1 blocks
==20799==    indirectly lost: 0 bytes in 0 blocks
==20799==      possibly lost: 0 bytes in 0 blocks
==20799==    still reachable: 0 bytes in 0 blocks
==20799==         suppressed: 0 bytes in 0 blocks
==20799==
==20799== For lists of detected and suppressed errors, rerun with: -s
==20799== ERROR SUMMARY: 1 errors from 1 contexts (suppressed: 0 from 0)

mtrace

只能检测内存泄漏及重复释放内存,centos未找到安装包

程序包含

mtrace

函数时会开启内存分配跟踪,

muntrace

关闭内存分配跟踪

mtrace需要运行程序才能生成跟踪日志,跟踪日志的路径需手动配置环境变量

MALLOC_TRACE

编译时需添加参数-g

$ export MALLOC_TRACE=./test.log
#运行程序
$ ./test
# 查看日志会有内存申请和释放的信息,如:@ ./test:[0x4005e4] + 0x1e96460 0x10
# 0x4005e4为内存地址,后边的+号表示申请内存
$ cat test.log
= Start
@ ./test:[0x4005e4] + 0x1e96460 0x10
= End
#查看内存地址对应哪行代码
$ addr2line -f -e test 0x4005e4
main
/home/mem_test/test.c:7
#使用mtrace检测是否存在内存泄漏
#mtrace <exe file> <log file>
$ mtrace ./test $MALLOC_TRACE
Memory not freed:
-----------------
           Address     Size     Caller
0x0000000001e96460     0x10  at /home/mem_test/test.c:7

原文作者:

edycm

原文地址:

http://t.csdn.cn/cajXS

(版权归原文作者所有,侵权留言联系删除)



版权声明:本文为m0_74282605原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。