这些小活动你都参加了吗?快来围观一下吧!>>
电子产品世界 » 论坛首页 » 嵌入式开发 » 软件与操作系统 » Linux系统调试篇——valgrind内存泄露检测

共2条 1/1 1 跳转至

Linux系统调试篇——valgrind内存泄露检测

高工
2023-10-30 09:48:16     打赏

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

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

valgrind下载安装

下载:

https://www.valgrind.org/downloads/

image.png

安装:

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

image.png

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

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

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





关键词: Linux     系统     调试     valgrind    

高工
2023-10-31 08:28:31     打赏
2楼

编程高科技原理


共2条 1/1 1 跳转至

回复

匿名不能发帖!请先 [ 登陆 注册 ]