19

I have a variable called x in GDB which I want to compare against a string.

gdb $ print $x
$1 = 0x1001009b0 "hello"

but a comparsion with

if $x == "hello"

doesn't work.

calquin
  • 421
  • 1
  • 4
  • 10
  • Related for C++ strings: https://stackoverflow.com/questions/10801112/gdb-conditional-breakpoint-on-arbitrary-types | https://stackoverflow.com/questions/45287838/gdb-breakpoints-with-multiple-conditions-on-non-native-types – Ciro Santilli OurBigBook.com Apr 16 '20 at 15:26

1 Answers1

27

As @tlwhitec points out: You could also use the built-in $_streq(str1, str2) function:

(gdb) p $_streq($x, "hello")

This function does not require GDB to be configured with Python support, which means that they are always available.

More convenient functions can be found in https://sourceware.org/gdb/onlinedocs/gdb/Convenience-Funs.html. Or use

(gdb) help function

to print a list of all convenience functions.


For older gdb's that lack the built-in $_streq function, You can define your own comparison

(gdb) p strcmp($x, "hello") == 0
$1 = 1

If you are unfortunate enough to not have the program running (executing a core file or something), you can do something to the effect of the following if your gdb is new enough to have python:

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

or:

(gdb) define strcmp
>py print cmp(gdb.execute("output $arg0", to_string=True).strip('"'), $arg1)
>end
(gdb) strcmp $x "hello"
0
matt
  • 5,364
  • 1
  • 25
  • 25
  • This will work only when debugging running process, but will not if debugging core dump. – ks1322 Sep 15 '11 at 07:21
  • (An alternative for non-running debugging was apparently added in an edit.) – StellarVortex Dec 30 '14 at 08:03
  • 4
    With python support you could also use the internal `$_streq(str1, str2)` function: `(gdb) p $_streq($x, "hello")` This was probably added later than this answer was posted, I can see it in gdb 7.7. – tlwhitec May 19 '15 at 15:55