コンピュータや音楽の事書いてます

valgrindを使ってみた

valgrindはやっかいなメモリ関連のエラーをコンパイル後のバイナリ実行中に検査してくれるツール。

検査したソース

#include <cstdio>

int main(){
        //int aaa[100];//valgrindではスタックのチェックはあまり?やってくれない
        int *aaa=new int[100];
        for(int i=0;i<500;i++){
                aaa[i]=i*2;
        }
        for(int i=0;i<500;i++){
                printf("%d ", aaa[i]);
        }
        printf("\n");
        //delete[] aaa;//delete忘れ
        return 0;
}

これで 
g++ test.cpp -ggdb
valgrind --leak-check=full ./a.out

==11142== Memcheck, a memory error detector.
==11142== Copyright (C) 2002-2008, and GNU GPL'd, by Julian Seward et al.
==11142== Using LibVEX rev 1878, a library for dynamic binary translation.
==11142== Copyright (C) 2004-2008, and GNU GPL'd, by OpenWorks LLP.
==11142== Using valgrind-3.4.0, a dynamic binary instrumentation framework.
==11142== Copyright (C) 2000-2008, and GNU GPL'd, by Julian Seward et al.
==11142== For more details, rerun with: -v
==11142== 
==11142== Invalid write of size 4
==11142==    at 0x40063C: main (test.cpp:7)
==11142==  Address 0x4c371c0 is 0 bytes after a block of size 400 alloc'd
==11142==    at 0x4A06487: operator new(unsigned long) (vg_replace_malloc.c:274)
==11142==    by 0x400619: main (test.cpp:5)
==11142== 
==11142== Invalid read of size 4
==11142==    at 0x400661: main (test.cpp:10)
==11142==  Address 0x4c371c0 is 0 bytes after a block of size 400 alloc'd
==11142==    at 0x4A06487: operator new(unsigned long) (vg_replace_malloc.c:274)
==11142==    by 0x400619: main (test.cpp:5)
0 2 4 6 8 10 12 14 16 18 20 22 24 26 28 30 32 34 36 38 40 42 44 46 48 50 52 54 56 58 60 62 64 66 68 70 72 74 76 78 80 82 
〜中略〜
958 960 962 964 966 968 970 972 974 976 978 980 982 984 986 988 990 992 994 996 998 
==11142== 
==11142== ERROR SUMMARY: 800 errors from 2 contexts (suppressed: 9 from 1)
==11142== malloc/free: in use at exit: 400 bytes in 1 blocks.
==11142== malloc/free: 1 allocs, 0 frees, 400 bytes allocated.
==11142== For counts of detected errors, rerun with: -v
==11142== searching for pointers to 1 not-freed blocks.
==11142== checked 161,992 bytes.
==11142== 
==11142== 
==11142== 400 bytes in 1 blocks are definitely lost in loss record 1 of 1
==11142==    at 0x4A06487: operator new[](unsigned long) (vg_replace_malloc.c:274)
==11142==    by 0x400619: main (test.cpp:5)
==11142== 
==11142== LEAK SUMMARY:
==11142==    definitely lost: 400 bytes in 1 blocks.
==11142==      possibly lost: 0 bytes in 0 blocks.
==11142==    still reachable: 0 bytes in 0 blocks.
==11142==         suppressed: 0 bytes in 0 blocks.

7行目10行目での範囲外アクセスが800回と、newした領域が400bytes リークしている事が分かった。