Debugging a Segfault from a core dump
What you'll learn: How to use GDB to inspect a "Core Dump" file to find the exact line of code that caused a program to crash after it has already finished running.
The "Crime Scene" Photo
Imagine you are a detective. Usually, when you use GDB, you are "undercover," watching the crime happen in real-time. But sometimes, a program crashes in a production environment where you weren't watching.
A Core Dump is like a high-resolution photo of the crime scene. It is a file generated by the operating system at the exact moment of a Segmentation Fault, containing the entire state of the program's memory—every variable, every pointer, and exactly which line was executing.
Enabling the Camera
By default, many systems don't save core dumps to save disk space. To tell Linux you want them, you usually run ulimit -c unlimited in your terminal. Once enabled, if your program crashes, you’ll see a message like Segmentation fault (core dumped). This creates a file (often named core or something similar).
Analyzing the Evidence
To inspect the crash, you don't run the program. Instead, you tell GDB to look at the "photo" alongside your original source code. You load it like this:
gdb ./my_program core
Once inside, GDB will immediately tell you which function and line caused the crash. You can use the backtrace (or bt) command to see the "path" the program took to get there.
#include <stdio.h>
void break_everything(int *ptr) {
// This will cause a Segfault because we are
// trying to write to a NULL address.
*ptr = 100;
}
int main() {
int *invalid_ptr = NULL;
break_everything(invalid_ptr);
return 0;
}
If you compile this with debugging symbols (-g) and it crashes, loading the core dump in GDB will point directly to the line *ptr = 100;. Even though the program is dead, you can type print ptr to see its value at the moment of impact. You’ll see it was 0x0, confirming why the crash happened.
Key takeaway
Core dumps allow you to perform "post-mortem" debugging by loading a snapshot of a crash into GDB to inspect variables and the call stack.