Debuggers are the best way for a programmer to find bugs. Print statements have been the first only way for most of us to debug our programs. However they are not as efficient as a debugger. With a debugger you can see the code executing live, you can inspect the value of variables, see which function called what, you can change values of variables on the fly and much more. Especially with C, where segmentation faults are not uncommon and where printf statements sometimes become useless, gdb is a must.
b <line number/function name>
new break point at line number or function. b test.c:100
breakpoint in file test.c line 100, b my_func
breakpoint at my_funcinfo b
display breakpointsd <n>
disable breakpoint nr <optional arguments>
run programl
list codep <var name><@n>
to print var[with sequence of n elements from array].p *test
print contents of pointer test, p arr@10
print 10 elements of arraybt
show backtrace (functions that called the current function and the one before etc)f <n>
switch to frame n, used usually after bt
to jump to previous function's contexts
step in (moves inside function under cursor or moves to next line)n
continue to next lineu
step out (moves outside function or loop)ret <val>
return from function with value valj <n>
jump to linemake
run makedis
disassemblec
continue running codeinfo local
show values of variables in local contextdisp <var>
display value of var after each lineundisp
stop displaying variablewatch <var>
break if var changesq
quitinfo threads
list threadsthread <n>
switch to thread ninfo args
list agrumentsni
execute one machine instruction but don't step into functionssi
execute one machine instruction
First for gdb to be able to debug your c program you'll need to compile it
with the -g
or -ggdb
flag which generates
debugging symbols. Sometimes you might need to reduce the optimization from
-O3
to -O0
so that code is less optimized but
easier to debug otherwise some values might be optimized out. To run gdb
run gdb ./my-program
. You can also use the --tui
flag which will also display your code at the same time.