← Back to Error Lab

Segmentation fault (core dumped)

Published 2026-05-04

Educational use only. Content explains errors and defensive fixes for systems you own or are authorised to test. Do not use any technique here to access data, accounts, or networks without permission.

Root Cause

A segmentation fault (segfault) is a specific kind of error caused by accessing memory that "does not belong to you." It is a hardware-enforced memory protection mechanism. Common causes in C and C++ include dereferencing a null pointer, attempting to write to a read-only portion of memory (like a string literal), accessing an array out of its bounds, or using a pointer after its memory has been freed (a dangling pointer). The operating system immediately terminates the program to prevent memory corruption.

Fix / Solution

Debugging segfaults usually requires a debugger like GDB or Valgrind. Run the program through Valgrind to identify exactly where the invalid memory access occurs. Review the code to ensure all pointers are properly initialized, array indices are strictly checked against their boundaries, and memory is not accessed after being freed. Always set pointers to NULL after freeing them.

Code Snippet

// ❌ Dereferencing a NULL pointer causes a segfault
int *ptr = NULL;
*ptr = 10; // CRASH!

// ✅ Check pointer validity before dereferencing
int *ptr = malloc(sizeof(int));
if (ptr != NULL) {
    *ptr = 10;
    free(ptr);
    ptr = NULL; // Prevent dangling pointer
}