Skip to content

/errors/c/segmentation-fault-core-dumped

Segmentation fault (core dumped) in a C program

The commands on this page have not been executed by our verification runner yet.updated
tool
C
exit code
139
versions
GCC, Clang, Linux (glibc)
os
linux, macos

Segmentation fault (core dumped) means the program accessed memory it is not allowed to touch, so the kernel sent it SIGSEGV and stopped it. The shell prints the message, and a core file may be written if core dumps are enabled. The usual causes are a NULL or uninitialized pointer, an array index past the end, or a pointer used after free(). The fastest way to find the line is to rebuild with -g -fsanitize=address and run again, or to run the program under gdb and type bt after the crash.

Example

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

int main(void) {
    char *name = NULL;           /* never allocated */
    strcpy(name, "ada");         /* write through a NULL pointer: SIGSEGV */
    printf("%s\n", name);
    return 0;
}
bash
gcc -o crash crash.c && ./crash
echo $?        # 139 = 128 + 11 (SIGSEGV)

Find the faulty line

bash
# AddressSanitizer: reports the invalid access, with file and line
gcc -g -fsanitize=address -fno-omit-frame-pointer -o crash crash.c
./crash

# gdb: stop at the crash and print the call stack
gcc -g -O0 -o crash crash.c
gdb -q ./crash -ex run -ex bt

# Valgrind (Linux): reports invalid reads and writes
valgrind ./crash

Core dumps

TaskCommand
Allow core files in this shellulimit -c unlimited
Where the kernel writes themcat /proc/sys/kernel/core_pattern
List and open cores (systemd)coredumpctl list, coredumpctl gdb
Open a core file with gdbgdb ./crash core

Sources