gdbWatchPoint
Conditional breakpoints
Written by Dr Greg Law | Last updated 11th Sep 2019

gdbprompt-dftest2

Sometimes you want to a breakpoint to happen only when certain conditions are true. Such as a session having started, a file or socket being open or an iteration being at a certain point. Conditional breakpoints can help with this.

Regexp, temporary and normal breakpoints can all be made conditional by adding the suffix:

if [CONDITION]

Here [CONDITION] is a boolean expression, which, in GDB is true if the result is nonzero, otherwise it is false. The condition can include a function call, the value of a variable or the result of any GDB expression.

A common use case is using a conditional breakpoint to pause execution of your program on the [N]th iteration of a loop by typing something like:

break foo if i == [N]

For example:

break foo if i == 4

You can also make an existing breakpoint conditional by using the condition command. If you have an existing breakpoint (say 2) then you can add a condition to it with:

condition 2 i == 4

Type help condition at the GDB prompt for more.

Get tutorials straight to your inbox
Receive Greg's fortnightly GDB tips & tricks directly in your inbox
Related content
  • Catch intermittent bugs in the act
    Can't reproduce a non-deterministic bug? This on-demand webinar illustrates how to obtain a 100% reproducible test case.
    Watch the webinar
  • Concurrency Defects Resolution
    New techniques to help quickly find and resolve defects in multithreaded and multiprocess applications
    Download the technical paper

A dedicated resource to learn about debugging in GDB by industry leader in debugging and founder of Undo

Meet Greg