トップページへ

gdbでアドレス指定で値を出力する方法

小粋空間 » Programming Language » C/C++ » gdbでアドレス指定で値を出力する方法

gdbでアドレス指定で値を出力する方法を紹介します。

1.問題点

下記のサンプルプログラムを作りました。

#include <iostream>
#include <unistd.h>
 
int main() {
    int i;
    int *p;
    int j = 0;
    p = &j;
    for (i = 0; i < 10000; i++ ) {
        std::cout << "OK" << std::endl;
        sleep(1);
        j++;
    }
    return 0;
}

アドレス変数pのアドレスを出力し、そのアドレスをgdbで指定して、指定したアドレスの先の値を出力したいのですが方法が分かりません。

ということで、gdbでアドレス指定で値を出力する方法を紹介します。

2.gdbでアドレス指定で値を出力する

アドレス指定で値を出力するには、"x"を利用します。

サンプルファイルをビルドします。

% g++ -g test.cpp

gdbを起動します。

% gdb ./a.out
GNU gdb (GDB) Red Hat Enterprise Linux 7.6.1-94.el7
Copyright (C) 2013 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 "ppc64-redhat-linux-gnu".
For bug reporting instructions, please see:
<http://www.gnu.org/software/gdb/bugs/>...
Reading sym
(gdb)bols from a.out...done.

ブレークポイントを指定します。ここでは12行目を指定します。

(gdb) b 12
Breakpoint 1 at 0x100009f0: file test.cpp, line 12.

スタートして12行目でブレークします。

(gdb) start
Temporary breakpoint 2 at 0x10000998: file test.cpp, line 7.
Starting program: ./a.out
 
Temporary breakpoint 2, main () at test.cpp:7
7           int j = 0;
Missing separate debuginfos, use: debuginfo-install glibc-2.17-157.el7.ppc64 libgcc-4.8.5-11.el7.ppc64 libstdc++-4.8.5-11.el7.ppc64

もう1回ループさせて変数jの値を更新します。

(gdb) c
Continuing.
OK
 
Breakpoint 1, main () at test.cpp:12
12              j++;

ポインタ変数pを出力します。

(gdb) p p
$2 = (int *) 0x3ffffffff080

これでアドレス0x3ffffffff080を指定して値を出力します。

(gdb) x 0x3ffffffff080
0x3ffffffff080: 0x00000000

もう一度繰り返してアドレスの値を出力すれば、値がインクリメントされていることが分かります。

(gdb) c
Continuing.
OK
 
Breakpoint 1, main () at test.cpp:12
12              j++;
(gdb) x 0x3ffffffff080
0x3ffffffff080: 0x00000001

ちなみに、xの後ろに"/回数"を付与すれば、指定回数分のメモリを出力することができます。

(gdb) x/10 0x3ffffffff080
0x3ffffffff080: 0x00000001      0xb7ff0d48      0x00003fff      0xb7fef938
0x3ffffffff090: 0x00000000      0x00000000      0x00000000      0x00000000
0x3ffffffff0a0: 0x00003fff      0xfffff370

« 前の記事へ

次の記事へ »

トップページへ