System Programming

Why Rust over C++? A Deep Dive into Memory Safety

Nov 05, 20236 min read

C and C++ have been the kings of system programming for many years. However, the necessity to manually manage memory (heap and stack) to keep performance under control has led to countless "Segmentation Fault" and "Use After Free" vulnerabilities.

The Ownership Model

Rust has a unique system that ensures memory safety without a "Garbage Collector" and without degrading background performance. It has three basic rules:

  • Each value in Rust has an owner.
  • There can only be one owner at a time.
  • When the owner goes out of scope, the value will be dropped.

The Power of the Borrow Checker

Rust's compiler acts as an attorney on your behalf. When you lend data without copying it (Borrowing), it prevents multiple references that have both read and write access to the data at the same time.

fn main() {
    let mut s = String::from("hello");
    let r1 = &s; // No problem, immutable reference
    let r2 = &s; // No problem, immutable reference
    // let r3 = &mut s; // ERROR! Cannot have mutable and immutable references simultaneously.
}

If you tried to ensure such safety in C++, you would likely need to use many mutexes or smart pointers. Rust provides this to you with zero-cost abstraction.

F
Ferivonus
Engineering the System Architecture.
RustSystem ProgrammingMemory Safety