Debugging C/C++ programs with GDB



To add debugging info to an executable generated by gcc:

gcc -g source.c

Amount of debugging info added by gcc can be controlled.
For minimal debug info use: -g1, for maximal: -g3


gdb a.out

To skip intro message add -q flag.

To attach gdb to a running process:

gdb a.out pid 



Setting a breakpoint

Set a breakpoint at specific line:

break line_number

If you have multiple source files you can specify one:

break source.c:line_number

Set a breakpoint on a function call:

break function_name
break source.c:function_name

You can make a breakpoint conditional by adding if condition to breakpoint definition. E.g.:

break 12 if x > 5

Removing a breakpoint

clear line_number
clear function_name

Versions with source_file_name work as well.

running and traversing

To start debugging an app run:


If you have set breakpoints, the app will stop at first of them.

command description
n go to the next line of program
s make a single step in execution, i.e. go into the function if another function is called at our current line or go to the next line.
c continue execution (i.e. go to the next breakpoint or finish

printing out variables

To print value of a specific variable:

print variable_name

To print array:

print *array_name@length

To print all function arguments with their values:

info args

To print all local variables with their values:

info locals

To print all global and static variables with their values:

info variables


To print out function calls that lead to current place:


To print frames: frame
To step into specific frame (e.g. to print out callers variables):

frame frame_number

To switch between frames one can also use: up and down




calling a function

While debugging a program one can call a function. To do it use:

call function_name(function_params)

E.g.: call print("some text\n")

heap consistency checking

To enable controlling of mallocated memory one can call:


The function has to be called before the first malloc.
To call it from gdb use:

call mcheck(0)

More info about mcheck:

For more info about gdb visit: