Conditional Breakpoints
Adding a simple breakpoint at a line will stop the running programming whenever that line of code is hit. But this might not be the requirement every time. Suppose we want to add a kind of breakpoint on a line that will get hit only when a condition is met, not always.
Let’s understand by example. Check the code below,
#include<iostream> int val = 0; void dummyFunction() { val= val+2; std::cout<<val<<std::endl; } int main(int argc, char ** argv) { for(int i = 0; i < 50; i++) dummyFunction(); return 0; }
Now suppose we want to set the breakpoint at line 8 and we want to get it hit when val is 50. To do that we need to add breakpoint with following command,
br <FILENAME>:<LINE NUM> if <CONDITION>
For Example,
(gdb) br Sample.cpp:8 if val==50 Breakpoint 1 at 0x400849: file Sample.cpp, line 8.
After this breakpoint when application runs, line number 8 will be hit many times before value of va is 50. But breakpoint will be hit on this line only when value of val is 50.
[showads ad=inside_post]
Frequently Asked:
- Compiling C++ with Debug Symbols – gdb debugger Tutorial & Examples
- How to attach gdb with running process
- Conditional Breakpoints and watchpoints | gdb debugger Tutorial and examples
- Remote Debugging Tutorial using gdb Debugger
If you check the current list of breakpoints, it will explain the stuff too i.e.
(gdb) info br Num Type Disp Enb Address What 1 breakpoint keep y 0x0000000000400849 in dummyFunction() at Sample.cpp:8 stop only if val==50 breakpoint already hit 1 time
Watchpoints
Watchpoints is a kind of breakpoint but it is set on a variable instead of any line. Suppose you set the watchpoint on a variable val i.e.
(gdb) watch val
Then whenever value of val will change watchpoint will be hit and it will display the old and new values. For example,
(gdb) watch val Hardware watchpoint 1: val (gdb) run Starting program: /home/varun/Documents/blog/unix/gdb/Sample Hardware watchpoint 1: val Old value = 0 New value = 2 dummyFunction () at Sample.cpp:8 8 std::cout<<val<<std::endl;
Disable and Enabling Breakpoints or watchpoints
A watchpoint can be enbaled and disabled by using enable and disable command i.e.
Reading symbols from Sample...done. (gdb) watch val Hardware watchpoint 1: val (gdb) info br Num Type Disp Enb Address What 1 hw watchpoint keep y val (gdb) disable 1 (gdb) info br Num Type Disp Enb Address What 1 hw watchpoint keep n val (gdb) enable 1 (gdb) info br Num Type Disp Enb Address What 1 hw watchpoint keep y val (gdb)