用Valgrind检测内存泄漏

有时候使用malloc或new分配内存空间后会因为各种原因忘记free或delete,而且这一段内存因为分配给了当前应用程序却没被收回而造成占用内存越来越多、可用内存越来越少。解决的办法就是检测内存泄漏并在恰当的地方释放分配的内存。
Valgrind就是一个检测内存泄漏的好工具,它可以找到具体哪条语句申请分配的内存没有被释放。
以如下程序为例:
#include <stdlib.h>
void foo(void)
{
  int *p = (int *)malloc(sizeof(int));
}
int main(int argc, const char *argv[])
{
  foo();
  return 0;
}
这段程序在foo函数中申请了内存但是却没有释放。
首先编译该程序,并且用-g参数包含调试符号:
gcc m.c -g
使用Valgrind检测内存泄漏可以用:
valgrind --leak-check=true ./a.out
会得到如下报告:
==3422== Memcheck, a memory error detector
==3422== Copyright (C) 2002-2010, and GNU GPL'd, by Julian Seward et al.
==3422== Using Valgrind-3.6.0.SVN-Debian and LibVEX; rerun with -h for copyright info
==3422== Command: ./a.out
==3422== 
==3422== 
==3422== HEAP SUMMARY:
==3422==     in use at exit: 4 bytes in 1 blocks
==3422==   total heap usage: 1 allocs, 0 frees, 4 bytes allocated
==3422== 
==3422== 4 bytes in 1 blocks are definitely lost in loss record 1 of 1
==3422==    at 0x4023F50: malloc (vg_replace_malloc.c:236)
==3422==    by 0x80483D5: foo (m.c:4)
==3422==    by 0x80483E5: main (m.c:8)
==3422== 
==3422== LEAK SUMMARY:
==3422==    definitely lost: 4 bytes in 1 blocks
==3422==    indirectly lost: 0 bytes in 0 blocks
==3422==      possibly lost: 0 bytes in 0 blocks
==3422==    still reachable: 0 bytes in 0 blocks
==3422==         suppressed: 0 bytes in 0 blocks
==3422== 
==3422== For counts of detected and suppressed errors, rerun with: -v
==3422== ERROR SUMMARY: 1 errors from 1 contexts (suppressed: 12 from 7)
这里报告泄漏了4 byte内存也就是在程序开始申请的1一个int所占的内存。
将申请内存释放,程序修改为:
#include <stdlib.h>
void foo(void)
{
  int *p = (int *)malloc(sizeof(int));
  free(p);
}
int main(int argc, const char *argv[])
{
  foo();
  return 0;
}
重新运行检测,得到报告为:
==3473== Memcheck, a memory error detector
==3473== Copyright (C) 2002-2010, and GNU GPL'd, by Julian Seward et al.
==3473== Using Valgrind-3.6.0.SVN-Debian and LibVEX; rerun with -h for copyright info
==3473== Command: ./a.out
==3473== 
==3473== 
==3473== HEAP SUMMARY:
==3473==     in use at exit: 0 bytes in 0 blocks
==3473==   total heap usage: 1 allocs, 1 frees, 4 bytes allocated
==3473== 
==3473== All heap blocks were freed -- no leaks are possible
==3473== 
==3473== For counts of detected and suppressed errors, rerun with: -v
==3473== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 12 from 7)
报告显示没有检测到内存泄漏,这就说明内存泄漏已经被解决。
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值