Valgrind检测非法访问内存

一 代码

#include<iostream>
#include<stdlib.h>
using namespace std;
void func(){
    int *x=(int *)malloc( 10 * sizeof ( int ) ) ;
    x[10]=0;
}
int main(){
    func();
    cout<<"done"<<endl;
    return 0;
}

二 编译并运行

[root@localhost charpter05]# g++ -g 0508test.cpp -o 0508
[root@localhost charpter05]# ./0508
done

三 用Valgrind检测非法访问内存

[root@localhost charpter05]# valgrind ./0508
==16719== Memcheck, a memory error detector
==16719== Copyright (C) 2002-2017, and GNU GPL'd, by Julian Seward et al.
==16719== Using Valgrind-3.15.0 and LibVEX; rerun with -h for copyright info
==16719== Command: ./0508
==16719==
==16719== Invalid write of size 4
==16719==    at 0x4008DE: func() (0508test.cpp:6)
==16719==    by 0x4008EE: main (0508test.cpp:9)
==16719==  Address 0x5a1a068 is 0 bytes after a block of size 40 alloc'd
==16719==    at 0x4C29EC3: malloc (vg_replace_malloc.c:309)
==16719==    by 0x4008D1: func() (0508test.cpp:5)
==16719==    by 0x4008EE: main (0508test.cpp:9)
==16719==
done
==16719==
==16719== HEAP SUMMARY:
==16719==     in use at exit: 40 bytes in 1 blocks
==16719==   total heap usage: 1 allocs, 0 frees, 40 bytes allocated
==16719==
==16719== LEAK SUMMARY:
==16719==    definitely lost: 40 bytes in 1 blocks
==16719==    indirectly lost: 0 bytes in 0 blocks
==16719==      possibly lost: 0 bytes in 0 blocks
==16719==    still reachable: 0 bytes in 0 blocks
==16719==         suppressed: 0 bytes in 0 blocks
==16719== Rerun with --leak-check=full to see details of leaked memory
==16719==
==16719== For lists of detected and suppressed errors, rerun with: -s
==16719== ERROR SUMMARY: 1 errors from 1 contexts (suppressed: 0 from 0)

四 分析

1 16719表示的是进程号

2 版本信息

==16719== Memcheck, a memory error detector
==16719== Copyright (C) 2002-2017, and GNU GPL'd, by Julian Seward et al.
==16719== Using Valgrind-3.15.0 and LibVEX; rerun with -h for copyright info
==16719== Command: ./0508

3 非法写内存,写操作内存是4个字节,发生错误时候的函数堆栈,说明错误发生在第6行

==16719== Invalid write of size 4
==16719==    at 0x4008DE: func() (0508test.cpp:6)
==16719==    by 0x4008EE: main (0508test.cpp:9)

4 程序泄露了40个字节的内存

==16719== LEAK SUMMARY:
==16719==    definitely lost: 40 bytes in 1 blocks
==16719==    indirectly lost: 0 bytes in 0 blocks
==16719==      possibly lost: 0 bytes in 0 blocks
==16719==    still reachable: 0 bytes in 0 blocks
==16719==         suppressed: 0 bytes in 0 blocks

5 该程序存在两个问题,一个是fun函数动态申请的堆内存没有释放,另外一个是对堆内存访问越界。这两个问题都被valgrind检测出来了。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值