gdb - 执行当前行而不继续

gdb - execute current line without moving on

这可能在其他地方被问过,但对 google 来说有点棘手。

我正在 gdb(或更具体地说是 cgdb)中调试如下代码:

if(something) {
  string a = stringMaker();
  string b = stringMaker();
}

当我逐步使用 'n' 时,光标将到达 'string b' 行。此时我可以检查 a 的值,但是 b 还没有被填充,因为该行还没有被执行。再次按下 'n' 将执行该行,但随后也会移出 if 循环并且 b 现在将超出范围。有没有一种方法可以在不继续执行当前行的情况下执行它,以便在它超出范围之前检查它的结果?

只需在代码中添加 b; 之后的行。即

if(something) {
  string a = stringMaker();
  string b = stringMaker();
  b; // Break point here
}

好吧,你总是可以

(gdb) p stringMaker(); 

考虑到 stringMaker() 是可访问的,无论您在哪一行。您可以执行任何类型的语句,即使这些变量在当前范围内,也可以涉及变量。对于更高级的用法,您可以使用 gdb 的内部变量(, 等)来存储某些结果,以便稍后在先前计算中涉及的变量超出范围时使用它。

最后上帝(不管是什么)派遣我们 gdb Python API。只需键入 py 并删除你的代码,以至于你会忘记你最初在做什么。

Another press of 'n' will execute that line, but will then also move outside the if loop and b will now be out of scope

问题是next执行了太多的指令,b变量变得不可用。您可以用多个 stepfinish 命令替换此单个 next,以实现更精细的调试并在构建 b 后立即停止。这是测试程序的示例 gdb 会话:

[ks@localhost ~]$ cat ttt.cpp 
#include <string>

int main()
{
  if (true)
  {
    std::string a = "aaa";
    std::string b = "bbb";
  }
  return 0;
}
[ks@localhost ~]$ gdb -q a.out 
Reading symbols from a.out...done.
(gdb) start 
Temporary breakpoint 1 at 0x40081f: file ttt.cpp, line 7.
Starting program: /home/ks/a.out 

Temporary breakpoint 1, main () at ttt.cpp:7
7       std::string a = "aaa";
(gdb) n
8       std::string b = "bbb";
(gdb) p b
 = ""
(gdb) s
std::allocator<char>::allocator (this=0x7fffffffde8f) at /usr/src/debug/gcc-5.1.1-20150618/obj-x86_64-redhat-linux/x86_64-redhat-linux/libstdc++-v3/include/bits/allocator.h:113
113       allocator() throw() { }
(gdb) fin
Run till exit from #0  std::allocator<char>::allocator (this=0x7fffffffde8f) at /usr/src/debug/gcc-5.1.1-20150618/obj-x86_64-redhat-linux/x86_64-redhat-linux/libstdc++-v3/include/bits/allocator.h:113
0x0000000000400858 in main () at ttt.cpp:8
8       std::string b = "bbb";
(gdb) s
std::basic_string<char, std::char_traits<char>, std::allocator<char> >::basic_string (this=0x7fffffffde70, __s=0x400984 "bbb", __a=...) at /usr/src/debug/gcc-5.1.1-20150618/obj-x86_64-redhat-linux/x86_64-redhat-linux/libstdc++-v3/include/bits/basic_string.tcc:656
656     basic_string<_CharT, _Traits, _Alloc>::
(gdb) fin
Run till exit from #0  std::basic_string<char, std::char_traits<char>, std::allocator<char> >::basic_string (this=0x7fffffffde70, __s=0x400984 "bbb", __a=...) at /usr/src/debug/gcc-5.1.1-20150618/obj-x86_64-redhat-linux/x86_64-redhat-linux/libstdc++-v3/include/bits/basic_string.tcc:656
0x000000000040086d in main () at ttt.cpp:8
8       std::string b = "bbb";
(gdb) p b
 = "bbb"