A structured lesson workspace with readable content, hands-on examples, and a clean path to completion.
A segmentation fault is the operating system's response to an invalid memory access. Your program tried to read or write an address it does not own. The CPU's memory management unit raised a hardware exception. The OS delivered SIGSEGV. Your process died. The causes are finite and well-known: NULL dereference, use-after-free, buffer overflow, stack overflow, writing to read-only memory, and wild pointer dereference. Every segfault you encounter will be one of these.
#include <stdio.h>#include <stdlib.h>#include <string.h>int main(void) {int cause = 1;switch (cause) {case 1: {int *p = NULL;*p = 42;break;}case 2: {int *p = malloc(sizeof(int));free(p);*p = 42;break;}case 3: {int arr[3] = {1, 2, 3};arr[1000000] = 42;break;}case 4: {char *s = "read only";s[0] = 'R';break;}case 5: {int *p = (int *)0xDEADBEEF;*p = 42;break;}}return 0;}
GDB shows the exact line: segfault_causes.c:11. The backtrace shows the call stack. In this case, it is just main. In a complex program, the backtrace reveals the chain of calls that led to the crash. Compile with -g to include debug symbols. Without -g, GDB shows addresses instead of line numbers, which is far less useful.
Initialize every pointer to NULL or a valid address. Check malloc and fopen return values. Free memory exactly once. Set pointers to NULL after free. Use ASan during development. Use Valgrind for leak detection. Compile with -Wall -Wextra -g. Run your test suite under ASan. These habits do not eliminate segfaults. They reduce them from daily occurrences to rare events, and they make the rare events immediately diagnosable.
Segfaults are not mysteries. They are invalid memory accesses with a finite set of causes. The tools exist to diagnose them in seconds: GDB for the crash site, ASan for the root cause, Valgrind for the memory history. Use them. Every time. The five minutes you spend in GDB saves the five hours you would spend adding printf statements. Next: exit statuses and the macros that standardize them.
Finish the lesson once you have worked through the material. This awards ★ 40 XP.