How do I set a conditional breakpoint in gdb, when char* x points to a string whose value equals "hello"?

CDebuggingGdbConditional Breakpoint

C Problem Overview


Can I specify that I want gdb to break at line x when char* x points to a string whose value equals "hello"? If yes, how?

C Solutions


Solution 1 - C

You can use strcmp:

break x:20 if strcmp(y, "hello") == 0

20 is line number, x can be any filename and y can be any variable.

Solution 2 - C

Use a break condition with $_streq (one of GDB's own [convenience functions](https://sourceware.org/gdb/current/onlinedocs/gdb/Convenience-Funs.html#Convenience-Funs "current convenience functions online documentation")):

break [where] if $_streq(x, "hello")

or, if your breakpoint already exists, add the condition to it:

condition <breakpoint number> $_streq(x, "hello")

[Since GDB 7.5 (long ago)](https://sourceware.org/git/gitweb.cgi?p=binutils-gdb.git;a=commit;h=a72c32530ec5ee0b1baf366ba99db5f2e83681cb "git commit, released 2012-08-17") you can use that and a handful of other native [convenience functions](https://sourceware.org/gdb/current/onlinedocs/gdb/Convenience-Funs.html#Convenience-Funs "current online documentation") for various string matching, including $_regex which supports the Python regex syntax:

$_memeq(buf1, buf2, length)
$_regex(str, regex)
$_streq(str1, str2)
$_strlen(str)

These are quite less problematic than having to execute the usual strcmp() injected to the process' stack, because that can have undesired side effects.

Alas, using the native functions is not always possible, because they rely on GDB being compiled with Python support. This is usually the default, but some constrained environments might not have it. To be sure, you can check it by running show configuration inside GDB and searching for --with-python. This shell oneliner does the trick, too:

gdb -n -quiet -batch -ex 'show configuration' | grep 'with-python'

Solution 3 - C

break x if ((int)strcmp(y, "hello")) == 0

On some implementations gdb might not know the return type of strcmp. That means you would have to cast, otherwise it would always evaluate to true!

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Question341008View Question on Stackoverflow
Solution 1 - CNathan FellmanView Answer on Stackoverflow
Solution 2 - CtlwhitecView Answer on Stackoverflow
Solution 3 - CTobias DomhanView Answer on Stackoverflow