Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to compare a stored string variable in GDB?

Tags:

debugging

gdb

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.

like image 731
calquin Avatar asked Sep 14 '11 22:09

calquin


People also ask

Which command is used in gdb to find the type of variable in C?

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.

What does P do in gdb?

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).

How do I change a variable value in gdb?

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.

Which command is used to stop execution in gdb?

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.


1 Answers

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
like image 178
6 revs, 2 users 68% Avatar answered Sep 22 '22 03:09

6 revs, 2 users 68%