GDB:如果变量等于值则中断

SIF*_*IFE 79 c gdb

当一个变量等于我设置的某个值时,我喜欢让GDB设置一个断点,我试过这个例子:

#include <stdio.h>
main()
{ 
     int i = 0;
     for(i=0;i<7;++i)
        printf("%d\n", i);

     return 0;
}
Run Code Online (Sandbox Code Playgroud)

GDB的输出:

(gdb) break if ((int)i == 5)
No default breakpoint address now.
(gdb) run
Starting program: /home/SIFE/run 
0
1
2
3
4
5
6

Program exited normally.
(gdb)
Run Code Online (Sandbox Code Playgroud)

就像你看到的那样,GDB并没有提出任何突破点,这可能与GDB有关吗?

mat*_*att 115

除了嵌套在断点内的观察点之外,您还可以在'filename:line_number'上设置单个断点并使用条件.我发现它有时更容易.

(gdb) break iter.c:6 if i == 5
Breakpoint 2 at 0x4004dc: file iter.c, line 6.
(gdb) c
Continuing.
0
1
2
3
4

Breakpoint 2, main () at iter.c:6
6           printf("%d\n", i);
Run Code Online (Sandbox Code Playgroud)

如果像我这样你厌倦了行号更改,你可以添加一个标签然后在标签上设置断点,如下所示:

#include <stdio.h>
main()
{ 
     int i = 0;
     for(i=0;i<7;++i) {
       looping:
        printf("%d\n", i);
     }
     return 0;
}

(gdb) break main:looping if i == 5
Run Code Online (Sandbox Code Playgroud)


imr*_*eal 28

您可以使用观察点(数据而不是代码的断点).

你可以从使用开始watch i.
然后使用它为其设置条件condition <breakpoint num> i == 5

您可以使用获取断点号 info watch

  • `(gdb) watch i 在当前上下文中没有符号“i”。` (3认同)
  • 你必须在代码中存在 `i` 的地方。尝试 `break main`、`run`、`c`、`s`(确保你通过声明的步骤),然后是答案中的命令。确保使用 `-g` 标志编译你的程序。(即带有调试信息) (2认同)

Ale*_*nho 8

首先,您需要使用适当的标志编译代码,从而使调试成为代码.

$ gcc -Wall -g -ggdb -o ex1 ex1.c
Run Code Online (Sandbox Code Playgroud)

然后用您喜欢的调试器运行代码

$ gdb ./ex1
Run Code Online (Sandbox Code Playgroud)

告诉我代码.

(gdb) list
1   #include <stdio.h>
2   int main(void)
3   { 
4     int i = 0;
5     for(i=0;i<7;++i)
6       printf("%d\n", i);
7   
8     return 0;
9   }
Run Code Online (Sandbox Code Playgroud)

在第5行中断并查看i == 5.

(gdb) b 5
Breakpoint 1 at 0x4004fb: file ex1.c, line 5.
(gdb) rwatch i if i==5
Hardware read watchpoint 5: i
Run Code Online (Sandbox Code Playgroud)

检查断点

(gdb) info b
Num     Type           Disp Enb Address            What
1       breakpoint     keep y   0x00000000004004fb in main at ex1.c:5
    breakpoint already hit 1 time
5       read watchpoint keep y                      i
    stop only if i==5
Run Code Online (Sandbox Code Playgroud)

运行程序

(gdb) c
Continuing.
0
1
2
3
4
Hardware read watchpoint 5: i

Value = 5
0x0000000000400523 in main () at ex1.c:5
5     for(i=0;i<7;++i)
Run Code Online (Sandbox Code Playgroud)