使用valgrind对代码进行内存泄露检测

代码可能存在内存泄露怎么办?

使用valgrind可以对代码进行内存泄露检测。

valgrind下载安装

下载:

安装:

1、tar –jxvf valgrind-3.21.0.tar.bz2

2、cd valgrind-3.21.0

3、./configure –prefix=/home/book/valgrind-3.21.0/install

4、make

5、make install

–prefix为指定安装路径,可以不指定,使用默认的,即执行./configure

内存泄露测试

测试程序test.c:

分配40个字节的buffer,越界访问buf[10].

#include < stdio.h >

#include < stdlib.h >

#include < unistd.h >

void test()

{

int *buf = (int *)malloc(10*sizeof(int));

buf[10] = 0x55;

}

int main()

{

test();

return 0;

}

编译:

gcc -g -o test test.c

编译时注意加上-g选项

使用valgrinid测试:

./valgrind –leak-check=yes ./test

结果显示,产生错误的地方在test.c的15行main函数中,即调用test()函数。具体的在test.c的第9行,test函数内,即buf[10] = 0x55;语句。

根据提示信息,可知valgrind检测到了2个错误:

存在无效的写入数据,即数组越界访问内存泄露,分配了40字节没有释放

发表评论