valgrind 内存泄露工具使用
安装软件
sudo apt-get install valgrind
测试算例
#include <stdlib.h>
void f(void)
{
int* x = malloc(10 * sizeof(int));
x[10] = 0; // problem 1: heap block overrun
// problem 2: memory leak -- x not freed
}
int main(void)
{
f();
return 0;
}
如果以下面的语句运行
gcc -g -o testValgrind testValgrind.c
valgrind --tool=memcheck --leak-check=yes ./testValgrind
其中valgrind
表示用的是memcheck
工具包,使用了该工具包的检测内存泄露功能,**注意在编译程序的时候加上-g选项,打印错误信息的时候会给出行号。**可得到下面的结果
==18284== Memcheck, a memory error detector
==18284== Copyright (C) 2002-2017, and GNU GPL'd, by Julian Seward et al.
==18284== Using Valgrind-3.13.0 and LibVEX; rerun with -h for copyright info
==18284== Command: ./testValgrind
==18284==
==18284== Invalid write of size 4
==18284== at 0x108668: f (testValgrind.c:6)
==18284== by 0x108679: main (testValgrind.c:12)
==18284== Address 0x522d068 is 0 bytes after a block of size 40 alloc'd
==18284== at 0x4C2FB0F: malloc (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==18284== by 0x10865B: f (testValgrind.c:5)
==18284== by 0x108679: main (testValgrind.c:12)
==18284==
==18284==
==18284== HEAP SUMMARY:
==18284== in use at exit: 40 bytes in 1 blocks
==18284== total heap usage: 1 allocs, 0 frees, 40 bytes allocated
==18284==
==18284== 40 bytes in 1 blocks are definitely lost in loss record 1 of 1
==18284== at 0x4C2FB0F: malloc (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==18284== by 0x10865B: f (testValgrind.c:5)
==18284== by 0x108679: main (testValgrind.c:12)
==18284==
==18284== LEAK SUMMARY:
==18284== definitely lost: 40 bytes in 1 blocks
==18284== indirectly lost: 0 bytes in 0 blocks
==18284== possibly lost: 0 bytes in 0 blocks
==18284== still reachable: 0 bytes in 0 blocks
==18284== suppressed: 0 bytes in 0 blocks
==18284==
==18284== For counts of detected and suppressed errors, rerun with: -v
==18284== ERROR SUMMARY: 2 errors from 2 contexts (suppressed: 0 from 0)
查看结果可以看出,在主函数的12行,子函数的第6行存在问题,地址对应0字节,子函数的第5行的问题在于空间没有释放.
主要的功能
Memcheck:主要检查的程序错误包括
(1)、使用未初始化的内存;
(2)、读写已经释放了的内存;
(3)、使用超过malloc分配的内存空间;
(4)、对堆栈的非法访问;
(5)、申请的空间是否有释放;
(6)、malloc/free/new/delete申请和释放内存的匹配;
(7)、src和dst指针的重叠;
(8)、将无意义的参数传递给系统调用。
参考文献: