CSE Roadmap

Core tier · about 3 hours · 7 parts

Part 5 of 7 · 2 min read

gdb

Think of a black-box recorder in an aircraft. After the crash, investigators read the last moments: the height, the speed and the instruments. They do not need to see the crash happen. The analogy stops in one place: a recorder keeps a limited history, while a debugger shows the state at the moment of the fault only and the call chain that led to it.

In plain words: gdb, the GNU debugger, runs a program and stops it when a signal arrives. The command bt (backtrace) prints the call stack: the chain of functions that were active (Level 7, the stack), with the file and line of each. To get line numbers, compile with -g, and keep -O0 so that the code matches the source. The program above was compiled with gcc -g -O0. Running gdb -batch -ex run -ex bt ./crash:

Program received signal SIGSEGV, Segmentation fault.
0x0000555555555180 in sum (n=0x0) at crash.c:8
8           total += n->value;      /* bug: no check for n == NULL */
#0  0x0000555555555180 in sum (n=0x0) at crash.c:8
#1  0x00005555555551e8 in main () at crash.c:16
$1 = (struct node *) 0x0                      (print n)
Cannot access memory at address 0x0           (print *n)

A worked example. Read it from the top. The signal is SIGSEGV. The faulting line is line 8 of crash.c, in the function sum, called from main at line 16 (the two frames of the backtrace). The argument n of the failing frame is 0x0, a null pointer, and print *n confirms that the address cannot be read. So the fix is clear: test n != NULL in the loop condition. The addresses 0x555555555180 are not stable: they change on every run when randomisation is on (Level 10), and gdb turns it off for its own run to make them repeatable.

The key lines. Three commands cover most cases: run (start), bt (the call chain) and print VARIABLE (the values). up and down move between frames, and break FUNCTION stops at a function before the fault.

Backtrace

A backtrace is the list of the function calls that are active at one moment, from the innermost (where the program stopped) to main, usually with the source file, line and arguments of each. It shows how the program arrived at the failing line.

Example: frame 0 sum at line 8, frame 1 main at line 16.

Check yourself: 1. Which compiler flag gives line numbers to gdb? 2. What does frame #1 tell you? 3. How did gdb show that the pointer was null?