上一篇已经完成了valgrind 的编译和安装。
此处将阐述一下valgrind的使用,Valgrind是一款用于内存调试、内存泄漏检测以及性能分析的软件开发工具。
此篇只简单介绍一下其中的内存检测功能。
编译,安装完valgrind后,valgrind就相当于linux系统中的一个命令一样,很方便使用。
添加测试代码test.c:
#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;
}
编译生成test,通过valgrind来检测内存信息,编译命令:gcc -g test.c -o test 注意编译时不要使用-c 选择不然会出现
: ./test :cannot execute binary file的问题。
[root@localhost test]# valgrind--trace-children=yes./test
打印信息如下:
==19182== Invalid write of size 4
==19182== at 0x804838F: f (test.c:6)
==19182== by 0x80483AB: main (test.c:11)
==19182== Address 0x1BA45050 is 0 bytes after a block of size 40 alloc'd
==19182== at 0x1B8FF5CD: malloc (vg_replace_malloc.c:130)
==19182== by 0x8048385: f (test.c:5)
==19182== by 0x80483AB: main (test.c:11)
命令的格式:valgrind options myProgram
options可以为--leak-check=yes|no,--num-callers,--leak-origin等等
options参数选项如下:
更多使用功能从官网知悉!
参考文档:http://www.valgrind.org/docs/manual/quick-start.html#quick-start.mcrun
使用示例:http://www.oschina.net/translate/valgrind-memcheck
http://www.cnblogs.com/wangkangluo1/archive/2011/07/20/2111273.html