Segmentation fault

Also known as: segfault

On this page 7

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 situationKernel decisionResult for the process
Page swapped out but mappedLoad page from diskContinues normally
Write to copy-on-write pageCopy page and update mappingContinues normally
Address in no mapped regionInvalid accessSIGSEGV with SEGV_MAPERR
Write to read-only mappingPermission violationSIGSEGV with SEGV_ACCERR
Execute on non-executable pagePermission violationSIGSEGV with SEGV_ACCERR
How the kernel classifies a page fault

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.

CauseWhat goes wrongTypical faulting address
Null pointer dereferencePointer was never set or allocation failedNear zero
Use after freeMemory is accessed after being releasedFreed or unmapped heap
Buffer overflowIndex runs past the end of an arrayBeyond the buffer
Stack overflowDeep or infinite recursion exhausts the stackStack guard page
Write to string literalCode modifies read-only dataRead-only data segment
Uninitialized pointerPointer holds random stack contentsArbitrary
Typical causes of segmentation faults

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.

Several neighboring conditions in memory management are easily confused with a segmentation fault. They differ in who detects them and whether they are recoverable.

ConditionTriggerNormal outcome
Segmentation faultInvalid or forbidden memory accessProcess receives SIGSEGV
Page faultPage not currently in physical memoryHandled transparently by kernel
Bus errorMisaligned access or truncated mapped fileProcess receives SIGBUS
Out of memoryNo physical memory or swap leftAllocation fails or OOM killer acts
General protection faultx86 protection rule violatedUsually reported as SIGSEGV
Related memory conditions and how they differ

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.