Rust's Safety Guarantees
Rust gets called a "memory-safe" language a lot. But what does that actually buy you? Knowing what the borrow checker stops, what it shrugs at, and where the seams are matters if you want to write Rust that holds up under hostile input.
What the Borrow Checker Prevents
The ownership and borrowing system eliminates three of the most dangerous classes of bugs at compile time:
1. Use-After-Free
fn main() { let s = String::from("hello"); let r = &s; drop(s); // println!("{}", r); // ERROR: s was moved/dropped, r is dangling}In C, this compiles silently and causes undefined behaviour. Rust refuses to build it. The borrow checker tracks every reference's lifetime and won't let one outlive the data behind it.
2. Data Races
use std::thread;
fn main() { let mut data = vec![1, 2, 3];
// This would be a data race if it compiled // let handle = thread::spawn(|| { // data.push(4); // ERROR E0373: closure may outlive the current function // // (and E0499 once main also pushes) // }); // data.push(5);
// The correct way: transfer ownership let handle = thread::spawn(move || { // data is now owned by this thread println!("{:?}", data); }); // data is no longer accessible here handle.join().unwrap();}Shared data is either immutable or exclusively owned, full stop. Data races vanish by construction.
3. Iterator Invalidation
fn main() { let mut v = vec![1, 2, 3, 4, 5];
// In C++, this is undefined behavior: // for (auto it = v.begin(); it != v.end(); ++it) // if (*it == 3) v.push_back(6); // Invalidates iterator!
// In Rust, the compiler prevents it: // for item in &v { // if *item == 3 { // v.push(6); // ERROR: cannot borrow `v` as mutable // } // }}These three guarantees are compile-time - they cost nothing at runtime. No garbage collector, no reference counting overhead, no runtime checks. The safety is encoded in the type system and verified before the program runs.
What Rust Does NOT Prevent
Rust's safety guarantees have important limits. The following bugs are perfectly possible in safe Rust:
Logic Bugs
fn celsius_to_fahrenheit(c: f64) -> f64 { c * 9.0 / 5.0 + 31.0 // Bug: should be + 32.0}The type system cannot catch incorrect business logic.
Deadlocks
use std::sync::{Arc, Mutex};
fn main() { let a = Arc::new(Mutex::new(1)); let b = Arc::new(Mutex::new(2));
let a2 = Arc::clone(&a); let b2 = Arc::clone(&b);
// Thread 1: locks a, then b let h1 = std::thread::spawn(move || { let _a = a2.lock().unwrap(); std::thread::sleep(std::time::Duration::from_millis(10)); let _b = b2.lock().unwrap(); // DEADLOCK if thread 2 holds b });
// Thread 2: locks b, then a let _b = b.lock().unwrap(); std::thread::sleep(std::time::Duration::from_millis(10)); let _a = a.lock().unwrap(); // DEADLOCK if thread 1 holds a}Data races, yes. Deadlocks, no. Avoiding them is on you, and it usually comes down to disciplined lock ordering.
Memory Leaks
use std::rc::Rc;use std::cell::RefCell;
// Create a reference cycle - memory leak!struct Node { next: Option<Rc<RefCell<Node>>>,}
fn main() { let a = Rc::new(RefCell::new(Node { next: None })); let b = Rc::new(RefCell::new(Node { next: Some(Rc::clone(&a)) })); a.borrow_mut().next = Some(Rc::clone(&b)); // Cycle: a -> b -> a
// Neither a nor b will ever be freed // Rc's reference count never reaches 0}Memory safety means nothing dangles. It doesn't mean everything gets freed. Cycles in Rc quietly pile up forever. Reach for Weak when you need to break one.
Panic and Abort
fn main() { let v = vec![1, 2, 3]; println!("{}", v[10]); // Runtime panic: index out of bounds}Bounds checks happen at runtime. Safe, in the sense that you panic instead of reading garbage memory. Still a crash, though, and a panicking server is a downed server.
Every unwrap(), expect() and slice index on attacker-controlled input is a potential denial of service for the same reason.
Resource Exhaustion
fn main() { let mut v = Vec::new(); loop { v.push(vec![0u8; 1_000_000]); // Eventually runs out of memory }}Integer Overflow and Truncation
fn main() { let len: u32 = "4294967295".parse().unwrap(); // u32::MAX, read at runtime let total = len + 1; // debug build: panic; release build: wraps to 0 let short = 300u32 as u8; // `as` silently truncates: 44, in every build println!("{} {}", total, short);}Overflow checks are on in debug builds and off by default in --release, where arithmetic wraps. as casts never check at all. Feed a wrapped length into an allocation size or an unsafe index and you've got a memory-safety bug again, which is how several real Rust CVEs started. Use checked_add, try_from and friends wherever a size comes from outside.
The Safety Spectrum
| Bug Category | Prevented by Rust? | Mechanism |
|---|---|---|
| Use-after-free | Yes | Ownership + lifetimes |
| Data races | Yes | Send + Sync traits |
| Buffer overflows | Mostly (bounds checking) | Runtime panics |
| Null pointer deref | Yes | Option type |
| Double free | Yes | Ownership |
| Iterator invalidation | Yes | Borrow checker |
| Deadlocks | No | N/A |
| Logic errors | No | N/A |
| Memory leaks | No (possible with Rc cycles) | N/A |
| Stack overflow | No | N/A |
| Resource exhaustion | No | N/A |
| Integer overflow | Partial (panics in debug, wraps in release) | overflow-checks, checked_* |
Unsound unsafe in a dependency | No | Auditing, cargo-geiger, miri |
| Supply-chain attacks | No | cargo-audit, cargo-vet, lockfiles |
What About unsafe?
unsafe opens every door the compiler bolted shut. One sloppy block, and you're back in C-territory: use-after-free, data races, the lot. Hence the scrutiny. Auditing techniques are the next lesson's problem.
The Safety Pyramid
Think of Rust's safety as layers:
- Type system (compile-time): Prevents most memory bugs
- Runtime checks (bounds, unwrap): Catches remaining issues with panics
- Unsafe audit (human review): Validates that
unsafeblocks are sound - Testing + fuzzing: Catches logic bugs and edge cases
- Dependency audit: Ensures libraries are trustworthy
No single layer carries the whole load. Security falls out of the stack, not any one piece of it.
Practical Implications
Rust's guarantees mean that entire vulnerability classes that plague C/C++ codebases simply cannot exist in safe Rust:
- No buffer overflow exploits (bounds checking)
- No use-after-free exploits (ownership system)
- No data race conditions (Send/Sync traits)
- No null pointer exploits (Option type)
Which is why Android, Linux kernel modules, and the major browsers keep shipping more Rust into their security-critical guts. The language nukes the bug class that Microsoft found behind about 70% of the CVEs it assigns each year, and that Chromium puts at around 70% of its high-severity security bugs.