A segmentation fault, often shortened to segfault, is the error that occurs when a process accesses a memory address it is not permitted to use, or uses a valid address in a forbidden way, and the operating system terminates it to protect the rest of the system. In memory management, it is the visible result of memory protection enforced jointly by the memory management unit and the kernel.
On Unix-like systems such as Linux and macOS, the kernel reports the event by delivering the signal SIGSEGV to the offending process, whose default action is to terminate the process and optionally write a core dump. Windows reports the equivalent condition as an access violation with the exception code 0xC0000005. The name survives from early systems that used memory segmentation, although modern systems detect the same class of errors mainly through paging.
How a segmentation fault is detected
Every memory access made by a user program uses a virtual address that the memory management unit (MMU) translates through the page table. Each page table entry records whether the page is present and which permission bits apply: read, write, execute and user or supervisor access. When the translation fails or the permissions do not allow the operation, the MMU raises a page fault exception and hands control to the kernel.
The kernel then decides whether the fault is legitimate. Many page faults are normal, for example demand paging of a file or a copy-on-write page. Only when the address lies outside every valid mapping of the address space, or the access violates the mapping protections, does the kernel convert the fault into a segmentation fault. The table below shows how the kernel classifies typical faults.
| Fault situation | Kernel decision | Result for the process |
|---|---|---|
| Page swapped out but mapped | Load page from disk | Continues normally |
| Write to copy-on-write page | Copy page and update mapping | Continues normally |
| Address in no mapped region | Invalid access | SIGSEGV with SEGV_MAPERR |
| Write to read-only mapping | Permission violation | SIGSEGV with SEGV_ACCERR |
| Execute on non-executable page | Permission violation | SIGSEGV with SEGV_ACCERR |
The two codes SEGV_MAPERR and SEGV_ACCERR let a debugger or a signal handler distinguish between an unmapped address and a permission violation, which is often the first clue when diagnosing a crash.
Common causes in program code
Segmentation faults are almost always programming errors in languages with manual memory handling, chiefly C and C++, or in unsafe code within other languages. Memory-safe languages such as Java, Python or safe Rust normally catch the same mistakes earlier and raise a language-level exception instead.
| Cause | What goes wrong | Typical faulting address |
|---|---|---|
| Null pointer dereference | Pointer was never set or allocation failed | Near zero |
| Use after free | Memory is accessed after being released | Freed or unmapped heap |
| Buffer overflow | Index runs past the end of an array | Beyond the buffer |
| Stack overflow | Deep or infinite recursion exhausts the stack | Stack guard page |
| Write to string literal | Code modifies read-only data | Read-only data segment |
| Uninitialized pointer | Pointer holds random stack contents | Arbitrary |
An important subtlety is that not every invalid access causes a segfault. If a buffer overflow or a use-after-free lands on memory that is still mapped and writable, the program silently corrupts data and may crash much later, far from the real bug. This undefined behavior is what makes memory errors dangerous and is the basis of many security exploits.
Segmentation fault compared with related memory errors
Several neighboring conditions in memory management are easily confused with a segmentation fault. They differ in who detects them and whether they are recoverable.
| Condition | Trigger | Normal outcome |
|---|---|---|
| Segmentation fault | Invalid or forbidden memory access | Process receives SIGSEGV |
| Page fault | Page not currently in physical memory | Handled transparently by kernel |
| Bus error | Misaligned access or truncated mapped file | Process receives SIGBUS |
| Out of memory | No physical memory or swap left | Allocation fails or OOM killer acts |
| General protection fault | x86 protection rule violated | Usually reported as SIGSEGV |
The key distinction is that a page fault is a normal hardware event, while a segmentation fault is the kernel’s verdict that the access was illegal. A bus error, in contrast, usually means the address exists but cannot be accessed in the requested form, for example a memory-mapped file that was truncated after mapping.
Diagnosing and preventing segfaults
The most effective diagnosis starts with a core dump or a debugger backtrace, which shows the exact instruction and call stack at the moment of the fault. On Linux, enabling core dumps and loading them in GDB, or reading the kernel log line that records the faulting address and instruction pointer, usually narrows the problem to a single function.
- AddressSanitizer instruments the program at compile time and reports buffer overflows and use-after-free at the first bad access.
- Valgrind Memcheck runs the program on a synthetic CPU and detects invalid reads, writes and leaks without recompilation.
- Compiler warnings and static analysis catch many uninitialized pointers before the program ever runs.
- Guard pages and stack protectors turn silent corruption into an immediate, debuggable crash.
Prevention relies on disciplined ownership of memory: initializing every pointer, checking allocation results, setting pointers to null after freeing them and using bounds-checked containers. Adopting a memory-safe language for new components removes most of these error classes entirely.
Handling SIGSEGV safely
A process can install a signal handler for SIGSEGV, but doing so is rarely appropriate. After a segmentation fault the program state is usually corrupted and untrustworthy, so a handler should limit itself to logging minimal information with async-signal-safe functions and then terminate. Returning from the handler normally re-executes the faulting instruction and causes an endless loop of faults.
Some specialized software deliberately uses segmentation faults as a mechanism. Garbage collectors, virtual machines and user-space paging libraries protect pages on purpose and catch the resulting faults to track writes or load data lazily. This technique requires careful design and is the exception rather than the rule.
The idea in brief
Every program on a computer is given its own set of rooms in memory. It may enter those rooms, but not the rooms of other programs or the locked rooms of the operating system.
A segmentation fault happens when a program tries to open a door it has no key for, often because of a mistake in its code. The operating system stops the program at once so the mistake cannot damage anything else. The crash is annoying, but it is a safety measure, not the cause of the problem.
A practical scenario
A small team maintains an image-processing service written in C that runs on Linux servers. After a new release, the service crashes a few times per day with the message that it was killed by signal 11, SIGSEGV, while most requests still succeed.
An engineer enables core dumps, collects one and opens it in GDB. The backtrace shows the crash inside a resize function, with a faulting address just past the end of a heap buffer. Rebuilding the service with AddressSanitizer and replaying the failing request reveals that images with an odd width cause a one-byte buffer overflow in a loop condition.
The fix is a single corrected comparison operator. After deployment, the crashes stop completely, and the team adds the problematic image sizes to its automated test suite so the same mistake cannot return unnoticed.