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.
The ptype [ARG] command will print the type. Show activity on this post. This question may be related: vtable in polymorphic class of C++ using gdb: (gdb) help set print object Set printing of object's derived type based on vtable info.
The usual way to examine data in your program is with the print command (abbreviated p ), or its synonym inspect . It evaluates and prints the value of an expression of the language your program is written in (see section Using GDB with Different Languages).
Use the set variable (gdb) and the assign (dbx) commands to change the value associated with a variable, memory address, or expression that is accessible according to the scope and visibility rules of the language. The expression can be any expression that is valid in the current context.
To stop your program while it is running, type "(ctrl) + c" (hold down the ctrl key and press c). gdb will stop your program at whatever line it has just executed. From here you can examine variables and move through your program. To specify other places where gdb should stop, see the section on breakpoints below.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With