Valgrind检测内存读写越界

一 点睛

内存读写越界是指访问了没有权限访问的内存地址空间,比如访问数组时越界,对动态内存访问超出了申请时内存的大小范围。

二 内存读写越界例子

#include<stdlib.h>
#include<iostream>
using namespace std;
int main(){
    int len=4;
    int *pt=(int *)malloc(len*sizeof(int));
    int *p=pt;
    for(int i=0;i<len;i++)
            p++;
    *p=5;
    cout<<"the value of p is "<<*p<<endl;
    return 0;
}

三 编译并运行

[root@localhost charpter05]# g++ -g 0511.cpp -o 0511
[root@localhost charpter05]# ./0511
the value of p is 5

四 用Valgrind检测内存

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

五 分析

1 下面这个输出说明第10行,进行了非法写错误。

==18335== Invalid write of size 4
==18335==    at 0x400948: main (0511.cpp:10)
==18335==  Address 0x5a1a050 is 0 bytes after a block of size 16 alloc'd
==18335==    at 0x4C29EC3: malloc (vg_replace_malloc.c:309)
==18335==    by 0x40091D: main (0511.cpp:6)

2 下面这个输出说明第11行,进行了非法读操作

==18335== Invalid read of size 4
==18335==    at 0x400952: main (0511.cpp:11)
==18335==  Address 0x5a1a050 is 0 bytes after a block of size 16 alloc'd
==18335==    at 0x4C29EC3: malloc (vg_replace_malloc.c:309)
==18335==    by 0x40091D: main (0511.cpp:6)

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值