Stopping a program

A debugger lets you pause a program and look inside. Your program is loaded, but not running yet.

Breakpoints and line-by-line execution

Level 1 of 13 · interactive GDB exercise · runs in your browser

Start this exercise

What you will learn

Stop a running program at a chosen place, advance it one line at a time, and read a variable while it is paused.

break main marks where to pause. run starts the program. next runs one line. print total shows a value.

The highlighted line is the one that runs next. It has not happened yet!

The exercise

Pause in main, then step until line 7 is next.

You work in a real GDB session on the program below. GDB has loaded the program. Nothing is running yet.

#include <stdio.h>

int main(void) {
    int apples = 3;
    int oranges = 4;
    int total = apples + oranges;
    total = total * 2;
    printf("total = %d\n", total);
    return 0;
}

main.c, compiled with gcc -g -O0 -std=c11 -Wall -fno-omit-frame-pointer -fno-stack-protector -no-pie -fno-pie for 32-bit x86 Linux.

GDB commands you will use

break <where>
Stop when execution reaches a function or line (b main, b 12).
run
Start the program from the beginning (r).
next
Run the current line; step over function calls (n).
print <expr>
Evaluate and show an expression (p total, p &x, p *a, p/x n).
list
Show source around the current line (l).
continue
Resume until the next breakpoint or exit (c).
info breakpoints
List breakpoints and watchpoints (i b).
help <command>
Explain a GDB command (help next). apropos <word> searches for commands.

Common mistakes

Try it in your browser