Valgrind检测内存读写越界

匿名 (未验证) 提交于 2019-12-02 23:34:01
版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/chengqiuming/article/details/90311919

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

 #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

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

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

文章来源: https://blog.csdn.net/chengqiuming/article/details/90311919
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!