A segmentation fault occurs when the CPU and operating system detect an attempt to access a memory region the program is not entitled to access. Memory regions are divided into segments. section 6.4.1 section 6.4.2
Raw pointers make the failure concrete: dereferencing a NULL pointer crashes immediately, while starting from a nonzero address still crashes when scanning reaches an illegal region. section 6.4.2
Listing 6.12 Attempting to scan a running program’s memory byte by byte
1 fn main() {
2 let mut n_nonzero = 0;
3
4 for i in 0..10000 {
5 let ptr = i as *const u8; #1
6 let byte_at_addr = unsafe { *ptr }; #2
7
8 if byte_at_addr != 0 {
9 n_nonzero += 1;
10 }
11 }
12
13 println!("non-zero bytes in memory: {}", n_nonzero);
14 }
A short Rust program converts integer addresses to raw pointers and dereferences them inside an unsafe block, demonstrating how an invalid access can crash. section 6.4.2
Scanning a process's memory
A loop scans addresses from 1 through 9,999 and counts nonzero bytes. Although it avoids address zero, the program still crashes before printing the count because many addresses are illegal. section 6.4.2
Virtual addresses
Printing the addresses of globals, locals, boxed values, and a function shows values scattered across a wide range, illustrating that a program works with virtual addresses rather than a simple contiguous region. section 6.4.2
