Linux下检测C程序内存问题--valgrind

一,Valgrind 是个开源的软件

下载地址:valgrind.org

Linux直接下载方式:sudo apt-get install valgrind    


二,Valgrind简介

Valgrind是一款用于内存调试、内存泄漏检测以及性能分析的软件开发工具。

三,Valgrind使用

结合GCC编译器使用

1)gcc 

-g:增加调试信息方便Valgrind精准定位

-00:关闭gcc优化,减少Valgrind误判 

2)valgrind

--tool=memcheck  使用内存检测工具,模式就是使用memcheck

--leak-check=full   显示完整的检测信息


四,简单的举例

#include <stdio.h>
#include <stdlib.h>

void func(void)
{
    char *x=malloc(4);
    x[5]=10;
}
int main(void)
{
    func();
    return 0;
}
gcc -g -00 test.c

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

调试输出信息:

==7072== Memcheck, a memory error detector
==7072== Copyright (C) 2002-2013, and GNU GPL'd, by Julian Seward et al.
==7072== Using Valgrind-3.10.1 and LibVEX; rerun with -h for copyright info
==7072== Command: ./test
==7072== 
==7072== Invalid write of size 1
==7072==    at 0x8048438: func (01test.c:8)
==7072==    by 0x8048447: main (01test.c:13)
==7072==  Address 0x41fe02d is 1 bytes after a block of size 4 alloc'd
==7072==    at 0x402A17C: malloc (in /usr/lib/valgrind/vgpreload_memcheck-x86-linux.so)
==7072==    by 0x804842E: func (01test.c:7)
==7072==    by 0x8048447: main (01test.c:13)
==7072== 
==7072== 
==7072== HEAP SUMMARY:
==7072==     in use at exit: 4 bytes in 1 blocks
==7072==   total heap usage: 1 allocs, 0 frees, 4 bytes allocated
==7072== 
==7072== 4 bytes in 1 blocks are definitely lost in loss record 1 of 1
==7072==    at 0x402A17C: malloc (in /usr/lib/valgrind/vgpreload_memcheck-x86-linux.so)
==7072==    by 0x804842E: func (01test.c:7)
==7072==    by 0x8048447: main (01test.c:13)
==7072== 
==7072== LEAK SUMMARY:
==7072==    definitely lost: 4 bytes in 1 blocks
==7072==    indirectly lost: 0 bytes in 0 blocks
==7072==      possibly lost: 0 bytes in 0 blocks
==7072==    still reachable: 0 bytes in 0 blocks
==7072==         suppressed: 0 bytes in 0 blocks
==7072== 
==7072== For counts of detected and suppressed errors, rerun with: -v
==7072== ERROR SUMMARY: 2 errors from 2 contexts (suppressed: 0 from 0)

at 0x8048438: func (01test.c:8)
显示了错误的位置

total heap usage: 1 allocs, 0 frees, 4 bytes allocated
提示了分配和释放内存的次数

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值