Memory Safety in Rust

rust programming memory-safety

Memory Safety in Rust

Rust guarantees memory safety at compile time. This is one of the language’s core features and eliminates entire classes of bugs that plague C and C++ programs.

As part of this, variables must be initialized before you can use them:

fn main() {
    let enigma: i32;
    println!("{}", enigma); // Error: use of possibly uninitialized variable
}

Conditional Initialization

The compiler is smart, but it can’t evaluate runtime conditions:

fn main() {
    let enigma: i32;
    if true {
        enigma = 42;
    }
    println!("enigma is {}", enigma); // Error - conditional evaluation at runtime
}

Even though we can see that the if true branch will always execute, the compiler treats this as a runtime condition and can’t guarantee initialization.

However, if all code paths initialize the variable, Rust is happy:

fn main() {
    let enigma: i32;
    if true {
        enigma = 42;
    } else {
        enigma = 6;
    }
    println!("enigma is {}", enigma); // This works!
}

The compiler can guarantee that enigma is assigned a value in all branches, so it allows the code to compile.

Why This Matters

This compile-time checking eliminates:

  • Use of uninitialized memory
  • Null pointer dereferences
  • Buffer overflows
  • Data races

All without the overhead of a garbage collector.