Skip to content
systemcoding.dev
Systems Programming

Debug Your First Segfault With gdb and a Core Dump

Turn Segmentation fault (core dumped) into a line number: compile with -g, enable core files, open the core in gdb, and read the backtrace and variables.

7 min read
Summarize in AI
Flat illustration of a debugger stopped at a breakpoint beside the register values, with the GNU, C and Arm logos.

A program that prints Segmentation fault (core dumped) has told you almost nothing, but it has also left you a file that tells you everything. The message means the program touched memory it was not allowed to touch, the kernel stopped it with a signal named SIGSEGV, and, if the system is set up for it, the kernel saved a snapshot of the process at that instant called a core dump. Opening that snapshot in the GNU debugger, gdb, shows the exact line that crashed, the chain of function calls that led there, and the values of the variables. This post walks through the whole thing on a program small enough to see at a glance.

The commands are for GDB 15 on a Linux 6.12 system, with GCC 14 and glibc 2.40. Where your system differs, usually in how core files are named and stored, the text says so.

A program that crashes

The program below sets a value through a pointer. One caller passes a valid pointer and another passes NULL, which is how a function ends up dereferencing memory at address zero.

crash.cc
#include <stdio.h>

static void set_value(int *p, int v)
{
    *p = v;
}

int main(void)
{
    int a = 0;
    int *missing = NULL;

    set_value(&a, 10);
    printf("a is %d\n", a);

    set_value(missing, 20);
    printf("not reached\n");
    return 0;
}

Compile it with debugging information and no optimization. The -g flag records source file and line numbers in the executable, and -O0 keeps the compiler from rearranging code so the debugger's view matches what you wrote:

Shell
gcc -std=c17 -g -O0 -Wall -o crash crash.c

Run it:

Text
a is 10
Segmentation fault (core dumped)

The first call worked and printed. The second one crashed, so not reached never appeared. The words core dumped say a core file was written, which is what you want. If you see only Segmentation fault with no core dumped, the system did not save one, and the next section fixes that.

Make sure a core file is saved

Two settings control whether you get a core dump, and both vary by machine.

The size limit. A shell limits core files by default, often to zero. Raise it for the current shell with:

Shell
ulimit -c unlimited

That affects only this shell and the programs it starts. To check, ulimit -c prints the current limit.

Where it goes. The file /proc/sys/kernel/core_pattern says what the kernel does with a dump. Read it:

Shell
cat /proc/sys/kernel/core_pattern

If it prints a plain name such as core, the kernel writes a file called core in the program's working directory. Many distributions instead set it to a pipe, such as |/lib/systemd/systemd-coredump %P %u %g %s %t 9999 %h, which hands the dump to a service that stores it compressed. On those systems the file does not appear in your directory, and you use coredumpctl to get at it instead. Both routes lead to the same gdb session.

On a system with a plain core pattern, run the program again after ulimit -c unlimited and a file named core appears next to crash. On a system with systemd, list the dumps with coredumpctl list and open the latest in gdb with coredumpctl gdb.

Open the core file in gdb

Give gdb the executable first and the core file second. The executable provides the code and the debugging information. The core provides the memory and registers at the moment of the crash.

Shell
gdb ./crash core

After some version and licence text, gdb loads the core and stops at the crash site, showing the location it died:

Text
Core was generated by `./crash'.
Program terminated with signal SIGSEGV, Segmentation fault.
#0  0x0000555555555171 in set_value (p=0x0, v=20) at crash.c:5
5	    *p = v;

Read that last pair of lines carefully, because it is the answer. The program died in the function set_value, at line 5 of crash.c, executing *p = v;. And gdb has already printed the arguments: p=0x0 means the pointer was null, and v=20 is the second call. Address 0x0000555555555171 is the machine instruction that faulted; its exact value differs on your system.

Find out how it got there

The line that crashed is rarely where the mistake is. The pointer was null because somebody passed a null pointer, so the question is who. The backtrace command, abbreviated bt, prints the chain of calls:

Text
(gdb) bt
#0  0x0000555555555171 in set_value (p=0x0, v=20) at crash.c:5
#1  0x00005555555551c8 in main () at crash.c:16

Frame 0 is where the crash happened. Frame 1 is the caller: main, at line 16, which is the line set_value(missing, 20);. That is the place to look. Move up one frame to inspect main's variables with frame 1 and info locals:

Text
(gdb) frame 1
#1  0x00005555555551c8 in main () at crash.c:16
16	    set_value(missing, 20);
(gdb) info locals
a = 10
missing = 0x0

missing = 0x0 is the cause, stated plainly: the variable that was passed in was null. a = 10 confirms the first call worked. You can print any expression with print, such as print missing, which shows $1 = (int *) 0x0, or print *p in frame 0, which fails with Cannot access memory at address 0x0.

The commands worth memorizing

CommandWhat it does
btPrint the call stack
frame NSelect frame number N
info localsShow local variables of the selected frame
print exprEvaluate and print an expression
listShow the source around the current line
info registersShow the CPU registers
quitLeave gdb

For a first segfault these are nearly all you need. The hard part is not the commands but the habit: look at the null or wild value, then walk up the stack to the code that put it there.

Running under gdb without a core file

If you cannot get a core file, or want to stop at the crash with the program still alive, run the program inside gdb and let it fault:

Shell
gdb ./crash

Then at the (gdb) prompt, type run. gdb stops when the signal arrives and prints:

Text
Program received signal SIGSEGV, Segmentation fault.
0x0000555555555171 in set_value (p=0x0, v=20) at crash.c:5
5	    *p = v;

From there, bt, frame and info locals work the same way. A live process also lets you set a breakpoint before the crash with break set_value and step through, which helps when the bad value is created long before it is used.

Why the line number might be missing

If gdb shows ?? () or function names without file and line numbers, the executable was built without -g, or the core does not match the executable. The core file records no code, only memory, so gdb must be given the same binary that crashed. Rebuild with -g, reproduce the crash, and use the new core. If you rebuild the program after the crash, the old core no longer matches it, and gdb will warn that the core file is newer or that the build id is different.

With optimization turned on, variables can appear as <optimized out> and lines can seem to jump around, because the compiler moved or removed code. Use -O0 for debugging a crash, and -Og, which keeps most optimizations that do not hurt debugging, once the crash is understood and you are checking the real build.

Common causes of a first segfault

A segmentation fault is the kernel's response to an access that does not match the memory's permissions or is outside any mapping. In beginner programs a few causes account for most of them.

  • A null pointer dereference, as above, usually from a function that returned NULL on failure and was not checked.

  • A buffer overflow or an index past the end of an array, which writes into memory the program does not own.

  • Use after free, where a pointer outlives the block it pointed to.

  • A stack overflow from unbounded recursion or an enormous local array, where gdb shows thousands of identical frames in bt.

  • Writing to a string literal, where a char *s = "text" is modified and the read-only memory refuses.

Each leaves a different trace in the backtrace and the variables, and the habit of reading both turns the crash into a clue. When the faulting address is small, such as 0x0 or 0x8, suspect a null pointer plus a field offset. When it looks like text, such as 0x6f6c6c6568 (the bytes for "hello" in little-endian), a string was written over a pointer.

When gdb is not enough

Some crashes do not appear at the faulting line, because earlier code corrupted memory and the crash is a late symptom. A backtrace through malloc or free with correct-looking calling code points to that. Then a tool that catches the first bad access, AddressSanitizer, is the next step, and the post on detecting heap bugs with it picks up where this one ends.

Also inDebugging
Share

Keep reading

Flat illustration of two options weighed side by side, with the macOS, Linux and Apple logos.
Kernels

Mach Traps vs BSD System Calls on macOS

Learn how macOS routes one trap instruction to either a Mach trap or a BSD system call, how the number sign and class decide, and why you should call libSystem.

8 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.