valgrind 内存泄露工具使用

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)、将无意义的参数传递给系统调用。

参考文献:

  1. 它人博客:ubuntu 上使用valgrind
  2. 官方说明书:The Valgrind Quick Start Guide
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值