Valgrind 的使用,找出linux的内存泄露和内存越界。

1. 下载代码

www.valgrind.org/

valgrind 3.7.0 (tar.bz2)

2.  安装

  tar jxf  *.tar.bz2

 make 

sudo make install 


ubuntu 上要安装 sudo apt-get install libc6-dbg  才行

3. 内存泄露诊断

编写代码 Virt.cpp

#include <unistd.h>
#include <stdio.h>
int main()
{
        for(int i=0;i<50;i++)
        {
                int *p = new int[1024];
                printf("time is: %d \n",i);
                sleep(1);
        }

        return 0;
}

编译: g++ -g Virt.cpp  -o Virt.exe

运行 valgrind --tool=memcheck  --leak-check=full ./Virt.exe

得到:

time is: 47
time is: 48
time is: 49
==15429==
==15429== HEAP SUMMARY:
==15429==     in use at exit: 204,800 bytes in 50 blocks
==15429==   total heap usage: 50 allocs, 0 frees, 204,800 bytes allocated
==15429==
==15429== 204,800 bytes in 50 blocks are definitely lost in loss record 1 of 1
==15429==    at 0x40271A9: operator new[](unsigned int) (vg_replace_malloc.c:343)
==15429==    by 0x80484D2: main (Virt.cpp:7)
==15429==
==15429== LEAK SUMMARY:
==15429==    definitely lost: 204,800 bytes in 50 blocks
==15429==    indirectly lost: 0 bytes in 0 blocks
==15429==      possibly lost: 0 bytes in 0 blocks
==15429==    still reachable: 0 bytes in 0 blocks
==15429==         suppressed: 0 bytes in 0 blocks
==15429==
==15429== For counts of detected and suppressed errors, rerun with: -v
==15429== ERROR SUMMARY: 1 errors from 1 contexts (suppressed: 17 from 6)


4. 内存越界诊断



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值