1

我正在研究 GDB 的观察点。我写了一个简单的测试代码如下:

int main(int argc, char **argv)
{
    int x = 30;
    int y = 10;

    x = y;

    return 0;
}

I build it via gcc -g -o wt watch.c. And then I started gdb and did following experiment:
    lihacker@lihacker-laptop:~/mySrc$ gdb ./wt
    GNU gdb (GDB) 7.3
    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-pc-linux-gnu".
    For bug reporting instructions, please see:
    <http://www.gnu.org/software/gdb/bugs/>...
    Reading symbols from /home/lihacker/mySrc/wt...done.
    (gdb) b main
    Breakpoint 1 at 0x80483a5: file watch.c, line 5.
    (gdb) run
    Starting program: /home/lihacker/mySrc/wt 

    Breakpoint 1, main (argc=<optimized out>, argv=<optimized out>) at watch.c:5
    5     int x = 30;
    (gdb) watch x
    Hardware watchpoint 2: x
    (gdb) c
    Continuing.

    Watchpoint 2 deleted because the program has left the block in
    which its expression is valid.
    0xb7e83775 in __libc_start_main () from /lib/tls/i686/cmov/libc.so.6
    (gdb) 

在我的测试代码中,变量“x”发生了变化,但 gdb 并没有停止。为什么观察点在这里不起作用?非常感谢。

4

1 回答 1

1

这个:

Breakpoint 1, main (argc=<optimized out>, argv=<optimized out>) at watch.c:5

建议您-O2在构建测试时使用或一些这样的标志。尝试构建-O0(这将明确禁用优化)。

即便如此,GDB 中也存在一个小故障(buglet)。这是我看到的:

(gdb) b main
Breakpoint 3 at 0x80483ba: file t.c, line 3.
(gdb) r

Breakpoint 3, main (argc=1, argv=0xffffca94) at t.c:3
3       int x = 30;
(gdb) watch x
Hardware watchpoint 4: x
(gdb) c
Hardware watchpoint 4: x

Old value = 0
New value = 10
main (argc=1, argv=0xffffca94) at t.c:8
8       return 0;
(gdb) c

Watchpoint 4 deleted because the program has left the block in
which its expression is valid.
0xf7e7cbd6 in __libc_start_main () from /lib32/libc.so.6

这不可能:x 的值从 30 变为 10,而不是从 0 变为 10。

如果我在 main 的第一条指令上设置断点,那么它会按预期工作:

(gdb) b *main
Breakpoint 1 at 0x80483b4: file t.c, line 2.
(gdb) r

Breakpoint 1, main (argc=1, argv=0xffffca94) at t.c:2
2   {
(gdb) watch x
Hardware watchpoint 2: x
(gdb) c
Hardware watchpoint 2: x

Old value = 0
New value = 30
main (argc=1, argv=0xffffca94) at t.c:4
4       int y = 10;
(gdb) c
Hardware watchpoint 2: x

Old value = 30
New value = 10
main (argc=1, argv=0xffffca94) at t.c:8
8       return 0;
(gdb) c

Watchpoint 2 deleted because the program has left the block in
which its expression is valid.
0xf7e7cbd6 in __libc_start_main () from /lib32/libc.so.6
于 2011-12-26T16:27:25.923 回答