Memory & Pointers

a segmentation fault

/ seg-fault /

Sooner or later every C programmer meets the words 'Segmentation fault' and a program that just died. It is the operating system's way of saying 'you tried to touch memory you were not allowed to touch'. The hardware noticed an invalid memory access and refused, and the OS killed the process rather than let it run wild.

More precisely, the memory-management hardware checks every access against what your process is permitted to do. When you read or write an address that is not mapped into your address space, or write to read-only memory, the hardware raises a fault; the kernel turns that into the signal SIGSEGV, whose default action is to terminate the process (often dumping core for later debugging). Common triggers all reduce to a bad address: dereferencing a null pointer, using a dangling or wild pointer, running off the end of an array or buffer, overflowing the stack with runaway recursion, or trying to modify a string literal in read-only memory.

Here is the crucial, honest part: a segmentation fault is a symptom, not the bug. It tells you that an invalid access happened here, but the real defect is usually earlier — the pointer went bad somewhere upstream, or an out-of-bounds write corrupted things long before the crash. Worse, undefined behaviour does not promise a crash at all: the same bad pointer might, on a different run or build, silently corrupt memory and never segfault. So treat a segfault as a starting clue, reach for a debugger or a sanitiser to find where the address actually went wrong, and never assume 'no segfault' means 'no bug'.

int *p = NULL; *p = 5; almost always segfaults, because address 0 is deliberately unmapped. But int a[3]; a[1000000] = 5; might segfault, or might silently corrupt some other memory — undefined behaviour, no guaranteed crash.

A null deref reliably faults; an out-of-bounds write may corrupt silently.

A segfault is the lucky outcome of a bad access — it stops the program at the scene. The unlucky outcome of the same undefined behaviour is silent corruption with no crash, surfacing far away. Find the root cause (where the pointer went bad) with a debugger or AddressSanitizer; the fault location is rarely the bug.

Also called
segfaultSIGSEGV記憶體區段錯誤區段錯誤