In this article we will discuss how to use breakpoints in gdb and check backtrace etc.

How to add breakpoints in gdb

Breakpoints can be added only at “gdb” prompt i.e.

To add a breakpoint in running application just press the “Ctrl-C” command to get the “gdb prompt back.
Otherwise you can also add breakpoints before executing the run command.

Adding break point on a line number i.e.

“break”, “br” ,”b” all are same.

Adding break point with a function name

For global functions,

For member functions,

Now if you have added the break point before executing “run” command just press do the run command.

Otherwise if you have added the breakpoint after stopping the running program using “Ctrl-C” , then press “c” to continue the application i.e.

How to check btacktrace / stacktrace using gdb

You can check the backtrace when a running code hits a breakpoint or when you stop the running application using “Ctrl-C”. But generally we check the backtrace when some break point is hit.

 

When a breakpoint is hit “gdb” prompt will come like this,

To check the backtrace use “bt” command

It will show backtrace as follows,`

It shows the frames in stack current frame is at top i.e. #0, to go to any other frame in stack use command “f <number of frame>” i.e

At this point you can print variables value , execute some code , also go forward and backward.

Checking Values while debugging

Use the command “print” or “p” to print the values when some break point is hit i.e.

Changing Values while debugging

Use the command “set” to change the values when some break point is hit i.e.

Execute Code while debugging

you can execute some code like some function when a break point is hit i.e. execute a global function ehen breakpoint is hit i.e.

It will execute the secondFunction().

Traversal When breakpoint is hit

To traverse over the code when a break point is hit use following commands,

  • n — Runs the next line in step over mode i.e. will not go inside any function just run the next line in current function.

  • s — Runs the next line in step in mode i.e. if next line is a function call then it will go inside that function.

 

To list out all breakpoints use command,

To delete a breakpoint use command

d <breakpoint number>

for example,

Thanks.