「c,c++」gdb でデバッグしてみる

C ビギナーの私がなんとなく gdbデバッグしてみたくなったので、調べてみました。
その時のメモです。

GDB: The GNU Project Debugger
< http://www.gnu.org/software/gdb/ >

ドキュメントは以下になる。
・Debugging with GDB
< http://sourceware.org/gdb/current/onlinedocs/gdb/ >

サンプル的なページもある。
・Sample Session - Debugging with GDB
< http://sourceware.org/gdb/current/onlinedocs/gdb/Sample-Session.html#Sample-Session >

ただ、↑ページで理解するのは、さすがに骨の折れる作業 ( 本当は読まんといけないが )・・・
なので、以下のページを参考にさせていただきました。
・Debugging with GDB - Table of Contents
< http://www.asahi-net.or.jp/~wg5k-ickw/html/online/gdb-5.0/gdb-ja_toc.html >


まず、デバッグするプログラムを用意する。

1  #include <stdio.h>
2  
3  void main(void)
4  {
5    char a = 'A';
6    char b[80] = "ABCDE";
7    int c = 0;
8  
9    printf("%c\n", a);
10   printf("%s\n", b);
11   printf("%d\n", c);
12 
13   c = 1;
14   printf("%d\n", c);
15 }

コンパイルして、実行ファイルにしておく。

gcc -g hello.c

デバッグ情報を生成するために "-g" オプションをつけておく。

gdb を起動する。引数にデバッグ対象の実行ファイルを指定する。

gdb a.out
GNU gdb (GDB) Red Hat Enterprise Linux (7.2-50.el6)
Copyright (C) 2010 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-redhat-linux-gnu".
For bug reporting instructions, please see:
<http://www.gnu.org/software/gdb/bugs/>...
Reading symbols from /usr/local/tmp/gcc/a.out...done.
(gdb)

ユーザからの入力を待っている状態になってます。
で、今回は初めてなので、「ブレークポイント貼ってそこで実行を止める」、「プログラム実行時
の変数の値を確認する」あたりのみやってみたいと思います。

ブレークポイントは "b < 行番号 >" で貼れるみたいです。
何も考えず 9 行目に貼っておく。

(gdb) b 9
Breakpoint 1 at 0x8048475: file hello.c, line 9.

※ "clear < 行番号 >" でブレークポイントを削除できるみたいです。

実行してみる。

(gdb) r
Starting program: /usr/local/tmp/gcc/a.out

Breakpoint 1, main () at hello.c:9
9         printf("%c\n", a);
Missing separate debuginfos, use: debuginfo-install glibc-2.12-1.107.el6_4.2.i686

ちゃんと 9 行目で止まってくれてます。

この段階で変数の内容を確認してみる。"p < 変数名 >"

(gdb) p a
$1 = 65 'A'
(gdb) p b
$2 = "ABCDE", '\000' <repeats 74 times>
(gdb) p c
$3 = 0

ちゃんと確認できてます。

ステップ実行してみる。

(gdb) s
A
10        printf("%s\n", b);
(gdb) s
ABCDE
11        printf("%d\n", c);
(gdb) s
0
13        c = 1;

今、どの行にいて、その内容についても表示してくれてます。

継続は "c" でいけるみたいです。
14 行目にブレークポイント貼って、"c" を押してみる。
ちゃんと c の値が変わっていることがわかる。

(gdb) c
Continuing.
A
ABCDE
0

Breakpoint 2, main () at hello.c:14
14        printf("%d\n", c);
(gdb) p c
$4 = 1

"info breakpoints" とかでブレークポイントの一覧も確認できる。

(gdb) info breakpoints
Num     Type           Disp Enb Address    What
1       breakpoint     keep y   0x08048475 in main at hello.c:9
        breakpoint already hit 1 time
2       breakpoint     keep y   0x080484b4 in main at hello.c:14
        breakpoint already hit 1 time

終了は "q" でいける。

簡単ですが、今日はこの辺りで。以上です。

コンパイラとかでっかいプログラムもこれでデバッグされてるんですかね・・・?
だとしたらかなり大変そう。たぶんそんなことはないんだろうけど・・・