Valgrind检测内存读写越界

一 点睛

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

二 内存读写越界例子

#include
#include
using namespace std;
int main(){
    int len=4;
    int *pt=(int *)malloc(len*sizeof(int));
    int *p=pt;
    for(int i=0;i

三 编译并运行

[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)

 

你可能感兴趣的:(C++)