A segmentation fault (often shortened to segfault) is a specific runtime error that occurs when a program tries to access a memory location that it is not allowed to touch. [1, 2]
When this happens, the computer's hardware detects the illegal access and alerts the operating system. To prevent the rogue program from corrupting data or crashing the entire system, the OS step in and immediately terminates the program, usually displaying a message like Segmentation fault (core dumped). [1, 2, 3]
Common Causes
Segfaults are incredibly common in lower-level programming languages like C and C++ because they give developers direct control over computer memory via pointers. The most frequent culprits include: [1, 2]
Dereferencing a Null Pointer: Trying to read or write to a pointer that points to NULL or nullptr (nothing).
Out-of-Bounds Array Access: Attempting to read or write to an index that doesn't exist (e.g., trying to access array[100] on an array that only holds 10 items).
Using Uninitialized Pointers: Using a pointer that was declared but never assigned a valid memory address.
Use-After-Free (Dangling Pointers): Trying to access a block of memory after you have already freed or deallocated it.
Stack Overflow: Exhausting the program's stack memory, which is usually caused by