11.3 シンボリックデバッガ(gdb)によるデバッグ

  4.プログラム例2のデバッグ(1)
 次に11-2節「デバッグライトによるデバッグ」で用いた11-2-4の例題プログラム (整数1から10までの奇数の数をかぞえるプログラム)を対象にgdbを適用してみましょう (実際のプログラムには行番号はついていません)。

 1  #include <stdio.h>
 2  
 3  int main(void){
 4        int count;     /* 奇数の数 */
 5        int odd;         /* 現在の奇数値 */
 6  
 7        count = 0;
 8        odd = 1;                /* 奇数の初期値 */
 9        while(odd != 10){     /* 10になるまで */
10              count++;         /* 奇数の数を加算 */
11              odd = odd+2;    /* 次の奇数へ */
12        }
13  
14        printf("count = %d\n", count);     /* 奇数の数を表示 */
15  }
 上記のプログラムをシンボリックデバッガgdbで解析した例を次に示します (以降はコメントです)。

$ gcc -g while.c
$ gdb a.out
GNU gdb 4.17.0.11 with Linux support
Copyright 1998 Free Software Foundation, Inc.
GDB is free software, covered by the GNU General Public License, and you are
welcome to change it and/or distribute copies of it under certain conditions.
Type "show copying" to see the conditions.
There is absolutely no warranty for GDB. Type "show warranty" for details.
This GDB was configured as "i386-redhat-linux"...
(gdb) run
Starting program: /home/miyao/Soft2/a.out 
                              #ここでCtrl+cを押して実行をストップ
Program received signal SIGINT, Interrupt.
main () at while.c:11
11 odd = odd+2;     /* 次の奇数へ */
(gdb) stack                 #どのような状態でストップしているかを表示。
#0 main () at while.c:11
#1 0x4002fcb3 in __libc_start_main (main=0x80483d0 , argc=1, 
argv=0xbffff844, init=0x8048298 <_init>, fini=0x804844c <_fini>, 
rtld_fini=0x4000a350 <_dl_fini>, stack_end=0xbffff83c)
at ../sysdeps/generic/libc-start.c:78
                              #これより、11行目のwhileループの中でストップしたことがわかる。
                                このループが無限ループになっている可能性が高い。
(gdb) quit
The program is running. Exit anyway? (y or n) y
 上記の例は、プログラムを強制終了させて、プログラムがどこで無限ループに陥っているかを解析していますが、これはプログラムが異常終了してしまった場合にも応用できます。つまり、Segmentation fault(core dumped)でプログラムが異常終了した時点で、 stackコマンドを入力すると、プログラムがどこで停止したかを調べることができます。