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へ変換すると良さげ。

雑感

頭良すぎだろ。惚れた。

4月 092009
 

launchd.plist を書く機会があったら Lingon を使うと便利。

以下の画像のように設定するだけで、Mac 起動時に svnserve が動くようになる。


sexylightbox

はずなんだけど、なぜかたまに起動時に下のエラーが出て svnserve プロセスが死んだりした。

Stray process with PGID equal to this dead job: PID 125 PPID 1 svnserve

とりあえず、下記の要素を追加してあげるとちゃんと立ち上がる。
GUIにはない要素なので、Expert Mode から追加する。

<key>AbandonProcessGroup</key>
<true/>

原因は、同じグループのプロセス強制終了に巻き込まれるからっぽい? ソース

まだよく分かってないけど。

なんにせよ、手書きで書くより数倍楽だワー。

 

MacPorts のインストールメモ。

インストール

コンパイル環境が必要らしいので、Xcode Tools をインストールしておく。

MacPortsのサイトへ行って、dmg をダウンロードする。

ダウンロードしてきた dmg を実行してインストール。

/opt/local にインストールされたことと環境変数を確認。

$ ls /opt/local
... ずらずら ...
$ cd
$ vi .bash_profile
...
... macports の環境変数を設定した云々と英語で書かれてる。...
...

環境変数が設定されていなかったら、設定してあげる。

$ vi .bash_profile
export PATH=/opt/local/bin:/opt/local/sbin:$PATH    # 追加
export MANPATH=/opt/local/share/man:$MANPATH    # 追加
$ source .bash_profile

アップデート

念のため、アップデートを試す。

$ sudo port -d selfupdate
$ sudo port -d sync

以上でおしまい。

参考: MacPorts WikiJP