Course contentsShow
← C
Lesson 833 of 1,21911. The Preprocessor and BuildFree lesson

Inspecting the call stack with `backtrace`

Inspecting the call stack with backtrace

What you'll learn: How to use the backtrace command to see the sequence of function calls that led to a specific point or a crash in your program.

The trail of breadcrumbs

Imagine you are hiking and reach a dead end. To figure out how you got there, you look back at the trail of breadcrumbs you left behind. In C programming, when your code crashes with a "Segmentation Fault" or hits a breakpoint, you are standing at that dead end. You know where you are, but you might not remember the sequence of function calls that led you there.

This sequence is called the call stack. Every time your program calls a function, it pushes a new "frame" onto the stack containing that function's local variables and return address. When the function finishes, that frame is popped off. Using GDB, we can peek at this stack to see the history of active functions.

Using the bt command

When your program is paused in GDB, simply type backtrace (or the shortcut bt). GDB will print a numbered list of functions. The function at the top (#0) is the one currently executing. The one below it (#1) is the function that called it, and so on, all the way down to main.

Consider this buggy code:

#include <stdio.h>

void calculate_log(int value) {
    int *ptr = NULL;
    *ptr = value; // This will cause a crash (Segfault)
}

void process_data(int n) {
    calculate_log(n);
}

int main() {
    process_data(42);
    return 0;
}

If you run this in GDB, it will crash inside calculate_log. By typing bt, you might see output like this:

#0  calculate_log (value=42) at main.c:5
#1  0x000055555555514e in process_data (n=42) at main.c:9
#2  0x000055555555516a in main () at main.c:13

Why this matters

Debugging is rarely about the line that crashed; it’s about the context. In the example above, calculate_log is where the error happened, but process_data is the function that provided the data.

A backtrace tells you the "who, what, and where" of your program's execution path. If a function works fine 99% of the time but crashes once, backtrace helps you identify the specific chain of events that triggered the failure.

Key takeaway

Use backtrace (or bt) in GDB to view the list of active function calls and trace the path your program took to reach its current state.