Why did it crash?

Outside a debugger this program just says Segmentation fault. Inside GDB, a crash is a stop: the program is frozen at the moment it went wrong.

Reading a crash: signal, backtrace and frames

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

Start this exercise

What you will learn

When a program dies, use the signal, the backtrace and frame selection to find the line of your own code that caused it and the data it was working on.

No breakpoint needed. Type run and GDB catches it. Then backtrace shows how the program got there.

The crash is often inside a library function. up walks out to your code, where the bad value came from.

The exercise

Run the program until it crashes, then find out which user's record caused it.

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

#include <stdio.h>
#include <string.h>

struct user {
    const char *name;
    const char *email;
};

struct user users[3] = {
    {"ada", "[email protected]"},
    {"bob", NULL},
    {"cy", "[email protected]"},
};

int email_length(const struct user *u) {
    return (int)strlen(u->email);
}

int main(void) {
    int total = 0;
    for (int i = 0; i < 3; i++) {
        total += email_length(&users[i]);
    }
    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

run
Start the program from the beginning (r).
backtrace
List the active function calls, innermost first (bt).
frame <n>, up, down
Select a frame to inspect. Does not move execution.
print <expr>
Evaluate and show an expression (p total, p &x, p *a, p/x n).
info args
Show the selected frame's arguments.
info locals
Show the selected frame's local variables.
x/s <addr>
Show the text (C string) stored at an address, e.g. x/s u->name.
print $_siginfo._sifields._sigfault.si_addr
The address the program tried to touch when it got the signal.

Common mistakes

Try it in your browser