Electric Fenceを試す。

はじめに

 メモリ系のバグには、問題点を発見するまでに苦労する。早期発見にツールを活用できればと思い、Electric Fenceを試してみた。
今回のサンプルはこちら

問題のあるソース

 下記ソースは、サイズが2である配列を動的に確保し、存在しない3つ目の配列にアクセスするソースである。

andre@andre-VirtualBox:~/work/efence$ cat outOfBound.c
#include<stdio.h>
#include<stdlib.h>

int
main(void)
{
    int *a = ( int * )malloc( 2 * sizeof( int ) );

    for( int i = 0; i <= 2; ++i )     ★ a[2]にもアクセスしてしまうため、他のデータを壊す恐れがある。
    {
        a[ i ] = i;
        printf( "%d\n", a[ i ] );
    }

    free( a );
    return 0;
}

Electric Fenceを使ったものとそうでないものを動作させ、比較してみる。

Electric Fenceを使ったもの

 Electric Fenceを使ったときの見え方を下記に示す。

andre@andre-VirtualBox:~/work/efence$ ./outOfBound_with_efence 

  Electric Fence 2.1 Copyright (C) 1987-1998 Bruce Perens.
0
1
Segmentation fault (コアダンプ)                      ★ Segvする
andre@andre-VirtualBox:~/work/efence$ gdb outOfBound_with_efence core
GNU gdb (Ubuntu/Linaro 7.3-0ubuntu2) 7.3-2011.08
Copyright (C) 2011 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.  Type "show copying"
and "show warranty" for details.
This GDB was configured as "i686-linux-gnu".
For bug reporting instructions, please see:
<http://bugs.launchpad.net/gdb-linaro/>...
Reading symbols from /home/andre/work/efence/outOfBound_with_efence...done.

warning: core file may not match specified executable file.
[New LWP 3034]

warning: Can't read pathname for load map: 入力/出力エラーです.
[Thread debugging using libthread_db enabled]
Core was generated by `./outOfBound_with_efence'.
Program terminated with signal 11, Segmentation fault.
#0  0x08048546 in main () at outOfBound.c:11
11	        a[ i ] = i;                           ★ バグの場所でSegvしている

Electric Fenceを使っていないもの

andre@andre-VirtualBox:~/work/efence$ ./outOfBound_without_efence 
0
1
2             ★ Segvしない
andre@andre-VirtualBox:~/work/efence$ 

感想

 当たり前のことを書くが、Electric Fenceを使わないと、メモリアクセス違反(上記ソースのように)していたとき、問題が発生した箇所と問題点が離れすぎていてわからない。なので、正常ルートくらいは使うべきではないか。