GDB Debugging

Compile with Debug Information

To allow gdb access to the source code (Provides debug symbols - Do not share publicly as it contains the source code).

gcc -g <file>

Look for / Fix Bugs

First, initialize gdb with the executable to debug.

gdb ./<executable> --tui

After gdb is ready, we can use the following commands:

CommandDescription
lay nextSwitch to the next layout (Enables TUI mode if disabled - Allows for reading the code while debugging both in C and ASM).
refRefresh (if a program prints to the terminal, it can break gdb’s interface).`
qQuit gdb.
b mainAdd a breakpoint at the main function.
bPlace a breakpoint at the current line.
b <N>Place a breakpoint at line N.
b +<N>Place a breakpoint N lines down.
b <fn>Place a breakpoint at fn function.
dDelete all breakpoints.
d <N>Delete breakpoint number N.
clear <fn>Clear the breakpoint set to fn function.
nExecute up to the next line in C. If a function call is found, execute the function completely.
sExecute up to the next line in C. (Jump over)
s <N>Run N lines.
uSame as n, but if in a loop, execute until the loop exits.
nextiExecute up to the next instruction (line in ASM).
rRun the program until a breakpoint or error is reached.
cContinue running the program until a breakpoint or error is reached.
x/i $pcExamine the previous instruction (View memory).
info registersRead the CPU registers used by the program.
btSee the call stack up to the current line. (How we got here, so to speak)
print sizeof(<variable>)Check the size of a struct/variable/pointer.
p <var>Print variable var value.
info breakList breakpoints.

Check for Memory Leaks

Use valgrind to check for lost memory.

valgrind --leak-check=full ./<executable>