如何比较GDB中存储的字符串变量?

cal*_*uin 14 debugging gdb

我在GDB中有一个名为x的变量,我希望将其与字符串进行比较.

gdb $ print $x
$1 = 0x1001009b0 "hello"
Run Code Online (Sandbox Code Playgroud)

但与...比较

if $x == "hello"
Run Code Online (Sandbox Code Playgroud)

不起作用.

mat*_*att 21

正如@tlwhitec所指出的:你也可以使用内置$_streq(str1, str2)函数:

(gdb) p $_streq($x, "hello")
Run Code Online (Sandbox Code Playgroud)

此函数不需要使用Python支持配置GDB,这意味着它们始终可用.

更方便的功能可以在https://sourceware.org/gdb/onlinedocs/gdb/Convenience-Funs.html中找到.或者使用

(gdb) help function
Run Code Online (Sandbox Code Playgroud)

打印所有便利功能的列表.


对于缺少内置$_streq函数的旧gdb ,您可以定义自己的比较

(gdb) p strcmp($x, "hello") == 0
$1 = 1
Run Code Online (Sandbox Code Playgroud)

如果你不幸没有运行程序(执行核心文件或其他东西),如果你的gdb足够新,你可以做一些以下的效果:

(gdb) py print cmp(gdb.execute("output $x", to_string=True).strip('"'), "hello") == 0
True
Run Code Online (Sandbox Code Playgroud)

要么:

(gdb) define strcmp
>py print cmp(gdb.execute("output $arg0", to_string=True).strip('"'), $arg1)
>end
(gdb) strcmp $x "hello"
0
Run Code Online (Sandbox Code Playgroud)

  • 使用python支持你也可以使用内部`$ _streq(str1,str2)`函数:`(gdb)p $ _streq($ x,"hello")`这可能是在这个答案发布之后添加的,我可以看到它在gdb 7.7中. (3认同)