Part 4 of 7 · 2 min read
A crash
Think of a lift that is told to go to floor 0 in a building that begins at floor 1. The control system refuses and stops the lift. The analogy stops in one place: a lift stops safely, and a process with a bad address is ended by the kernel because it cannot be made to continue.
In plain words: A program that reads or writes an address that is not mapped (or that is mapped without the right permission) causes a page fault (Level 6). The kernel looks at the address, finds that no mapping allows the access, and sends the process SIGSEGV (segmentation fault). Address 0 is never mapped, so a null pointer always faults. The program below walks a list of three nodes but never checks for the end.
#include <stdio.h>
struct node { int value; struct node *next; };
static int sum(struct node *n) {
int total = 0;
while (1) {
total += n->value; /* bug: no check for n == NULL */
n = n->next;
}
return total;
}
int main(void) {
struct node c = {3, NULL}, b = {2, &c}, a = {1, &b};
printf("sum = %d\n", sum(&a));
return 0;
}
$ ./crash
Segmentation fault (exit status 139)
A worked example. The list is a -> b -> c -> NULL with values 1, 2, 3. The loop adds 1, 2 and 3, then sets n to the next of c, which is NULL, and tries to read n->value. That read is at address 0, the fault happens, and the kernel sends SIGSEGV: exit status 139 = 128 + 11. Notice that the program printed nothing, because the printf line comes after the call to sum. The shell's message "Segmentation fault" and the status are all the evidence without a debugger, and the next section turns this into a line number.
The key lines. A crash is a symptom with a cause in the program's logic: here a missing end check. The kernel's action (the page fault of Level 6) is the same for a null pointer, a freed pointer or a stack overflow (Level 7).
Segmentation fault
A segmentation fault is the error that occurs when a process accesses memory that it may not access: an unmapped address, or a mapped page with the wrong permission. The kernel reacts with the signal SIGSEGV, which by default ends the process and may dump its memory to a core file.
Example: reading n->value with n equal to NULL accesses address 0 and raises SIGSEGV.
Check yourself: 1. Why does a null pointer always cause a page fault? 2. Which exit status does a segmentation fault give? 3. Why did the program print nothing?