liveBook · Manning

Segmentation fault

As explained in Rust in Action: Systems programming concepts and techniques

A segmentation fault is an execution failure caused by attempting to access a memory region without permission or outside its valid bounds.

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

How Rust in Action: Systems programming concepts and techniques covers it

How deep it goes
Defines the CPU-level failure and demonstrates it through NULL and arbitrary-address dereferences, without detailing recovery strategies.
Examples
Uses NULL-pointer dereferencing, byte-by-byte memory scans, and printed addresses of stack, heap, global, and function values.
What it assumes
Assumes prior familiarity with pointers and introduces raw-pointer dereferences within unsafe blocks.
What you can do after
Evaluate/understand why an invalid raw-pointer access crashes and distinguish virtual addresses from valid accessible memory.
How it connects
Connects segmentation faults with virtual memory, pointers, unsafe blocks, the operating system, and the memory-management unit.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Rust in Action: Systems programming concepts and techniques. The section links point to the parts of the book it draws on.