gdb(1)

Development tool

The GNU debugger: start a program, stop it on a line, read its variables and the call stack at the moment it crashes.

Synopsis
gdb [options] program

Description

gdb runs your program under its control. It can stop it on a line, move it forward one step at a time, print the value of any variable, and above all tell you where it stopped when it crashes. For gdb to know your variable names and line numbers, compile with -g.

Commands to know

CommandEffect
run (or r)starts the program, with its arguments if it takes any: run file.txt
btprints the call stack, from the most recent call to the oldest
break 12sets a breakpoint on line 12 of the current file
break my_functionstops on entry to the function
next (or n)runs the current line without stepping into the functions it calls
step (or s)runs the current line, stepping into functions
print x (or p x)prints the value of an expression
continue (or c)resumes until the next breakpoint
quit (or q)exits gdb

Interactively, you type these commands one at a time at the (gdb) prompt. For a quick diagnosis, -batch chains them from the command line and exits at the end.

Example

sum.c
#include <stdio.h>
int main(void){    int total = 0;
    for (int i = 1; i <= 4; i++)        total += i * i;    printf("%d\n", total);    return 0;}
Terminal
$ gcc -g sum.c -o sum$ gdb -q -batch -ex 'break 8' -ex run -ex 'print i' -ex 'print total' -ex continue -ex 'print total' ./sumBreakpoint 1 at 0x40065c: file sum.c, line 8.warning: Error disabling address space randomization: Operation not permitted[Thread debugging using libthread_db enabled]Using host libthread_db library "/lib/aarch64-linux-gnu/libthread_db.so.1".
Breakpoint 1, main () at sum.c:88	        total += i * i;$1 = 1$2 = 0
Breakpoint 1, main () at sum.c:88	        total += i * i;$3 = 1

At the first stop, line 8 has not run yet: i is 1 and total is still 0. On the second pass, total has received 1 * 1. The Error disabling address space randomization warning means gdb runs inside a container that does not let it turn randomization off; it does not affect the session.

Pitfalls

  • Without -g, gdb sees neither lines nor variables: the call stack shows only addresses.

  • With -O2, the compiler reorganizes the code and some variables print as <optimized out>. Debug at -O0, the default.

  • After a crash inside the C library (strlen, printf), the top of bt is not your code. Go down to the first frame that names your file.

Now write it yourself.