6.9 Comparison with C Memory Management

6.9.1 Memory Safety Guarantees

Rust eliminates many common errors that are prevalent in C:

  • Memory Leaks: Rust automatically frees memory when it goes out of scope.
  • Dangling Pointers: The borrow checker prevents references to invalid memory.
  • Double Frees: Ownership rules prevent freeing memory multiple times.
  • Buffer Overflows: Bounds checking prevents writing outside allocated memory.

6.9.2 Concurrency Safety

Rust's ownership model enables safe concurrency. Rust uses the Send and Sync traits to enforce thread safety at compile time. Types that are Send can be transferred across thread boundaries, and Sync types can be safely shared between threads.

use std::thread;

fn main() {
    let s = String::from("hello");
    let handle = thread::spawn(move || {
        println!("{}", s);
    });
    handle.join().unwrap();
}

The compiler ensures that data accessed by multiple threads is handled safely.

6.9.3 Zero-Cost Abstractions

Rust's abstractions compile down to efficient machine code, often matching or exceeding the performance of equivalent C code.