Linux下检测程序内存泄漏

本文介绍了如何在Linux环境下使用valgrind工具检测内存泄漏。通过编译带有内存泄漏的C语言程序,然后运行valgrind,可以详细地查看到哪些内存未被释放,包括内存损失的具体位置和大小。此外,还展示了valgrind如何检测重复free和未初始化内存写入的问题,强调了即使free和malloc数量相等也可能存在内存问题。
摘要由CSDN通过智能技术生成

Linux下检测程序内存泄漏

工具:valgrind

Linux下载方式:yum install valgrind

内存泄漏:程序在heap上分配了内存却没有释放

写一个c语言内存泄漏程序:

#include <stdlib.h>
void f()
{
   
	int *t=malloc(sizeof(int)*10);
}
int main()
{
   
    int *array = malloc(10*sizeof(int));
    f();	
    return 0;
}	

很简单的一个程序,f()和main中都有malloc申请内存但是没有释放,故运行该程序会造成内存泄漏。

编译后生成a.out文件: gcc -g -o a.out test.c

运用valgrind检测内存泄漏:

 valgrind --tool=memcheck --leak-check=full  ./a.out

运行结果:

[root@jessy /]#  valgrind --tool=memcheck --leak-check=full  ./a.out
==14588== Memcheck, a memory error detector
==14588== Copyright (C) 2002-2017, and GNU GPL'd, by Julian Seward et al.
==14588== Using Valgrind-3.15.0 and LibVEX; rerun with -h for copyright info
==14588== Command: ./a.out
==14588== 
==14588== 
==14588== HEAP SUMMARY:
==14588==     in use at exit: 80 bytes in 2 blocks
==14588==   total heap usage: 2 allocs, 0 frees, 80 bytes allocated
==14588== 
==14588== 40 bytes in 1 blocks are definitely lost in loss record 1 of 2
==14588==    at 0x4C29F73: malloc (vg_replace_malloc.c:309)
==14588==    by 0x400556: main (test.c:8)
==14588== 
==14588== 40 bytes in 1 blocks are definitely lost in loss record 2 of 2
==14588==    at 0x4C29F73: malloc (vg_replace_malloc.c:309)
==14588==    by 0x40053E: f (test.c:4)
==14588==    by 0x400564: main (test.c:9)
==14588== 
==14588== LEAK SUMMARY:
==14588
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值