Valgrind検出メモリ読み書き限界
2729 ワード
ほんの少し
メモリ読み書き境界とは、配列へのアクセス時に境界を越え、動的メモリへのアクセスが申請時のメモリのサイズ範囲を超えたなど、アクセス権限のないメモリアドレス空間にアクセスすることです.
二メモリ読み書き限界例
3つのコンパイルと実行
四用Valgrind検出メモリ
五分析
1次の出力は10行目を説明し、不正な書き込みエラーを行いました.
2次の出力は11行目を説明し、不正な読み取り操作を行った
メモリ読み書き境界とは、配列へのアクセス時に境界を越え、動的メモリへのアクセスが申請時のメモリのサイズ範囲を超えたなど、アクセス権限のないメモリアドレス空間にアクセスすることです.
二メモリ読み書き限界例
#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
3つのコンパイルと実行
[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)