valgrind とは?

linux 環境で動く超強力なメモリデバッガー。
メモリリークや、セグメンテーション違反を起こしている正確な位置を教えてくれる。

以下、使い方メモ。
使用バージョンは、valgrind-3.2.1

メモリリーク検出など

$ valgrind --leak-check=full ./program arg1 arg2

ヒーププロファイラ

$ valgrind --tool=massif ./program arg1 arg2

メモリをデバッグしてみる

1. バッファオーバーランとメモリリークを行うソースコードを記述

$ vi main.cpp
#include <stdio.h>
 
int main()
{
    int *a = new int[2];
 
    a[2] = 0; // バッファオーバーラン
 
    return 0; // メモリリーク
}

2. コンパイルする

$ g++ main.cpp -g

3. 検証する

$ valgrind --leak-check=full ./a.out
 
... 省略 ...
 
・バッファオーバーラン検出
==10945== Invalid write of size 4
==10945==    at 0x80484AA: main (main.cpp:7)
==10945==  Address 0x410E030 is 0 bytes after a block of size 8 alloc'd
==10945==    at 0x40057F5: operator new[](unsigned) (vg_replace_malloc.c:195)
==10945==    by 0x80484A0: main (main.cpp:5)
==10945==
==10945== ERROR SUMMARY: 1 errors from 1 contexts (suppressed: 17 from 1)
==10945== malloc/free: in use at exit: 8 bytes in 1 blocks.
==10945== malloc/free: 1 allocs, 0 frees, 8 bytes allocated.
==10945== For counts of detected errors, rerun with: -v
==10945== searching for pointers to 1 not-freed blocks.
==10945== checked 87,724 bytes.
 
・メモリリーク検出
==10945== 8 bytes in 1 blocks are definitely lost in loss record 1 of 1
==10945==    at 0x40057F5: operator new[](unsigned) (vg_replace_malloc.c:195)
==10945==    by 0x80484A0: main (main.cpp:5)
==10945==
==10945== LEAK SUMMARY:
==10945==    definitely lost: 8 bytes in 1 blocks.
==10945==      possibly lost: 0 bytes in 0 blocks.
==10945==    still reachable: 0 bytes in 0 blocks.
==10945==         suppressed: 0 bytes in 0 blocks.
==10945== Reachable blocks (those to which a pointer was found) are not shown.
==10945== To see them, rerun with: --show-reachable=yes

ヒーププロファイラを試してみる

1. massifモードで起動する

$ valgrind --tool=massif ./a.out

2. massif.pid.ps ファイルが作成されている。Postscriptでは見づらいので、PDFへ変換すると良さげ。

雑感

頭良すぎだろ。惚れた。

 Leave a Reply

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <img localsrc="" alt=""> <pre lang="" line="" escaped="" highlight="">