Memory-Safe Languages
Memory Safety & Debugging · Memory & Systems track
5 min read
In this module
Preventing Bugs by Design
The memory errors from the first lesson — buffer overflows, use-after-free, double-free, uninitialised reads — all exist because C and C++ hand programmers direct, unchecked access to memory. Other languages head these bugs off through different mechanisms, each with its own trade-offs.
Memory-safe languages take the same problem space (track allocations, prevent invalid pointers, free memory at the right time) and solve it differently — through ownership, garbage collection, or runtime bounds checks. Each pays a different price.
Rust: Compile-Time Safety Without GC
Rust prevents memory errors with its ownership system and borrow checker, enforced entirely at compile time with zero runtime cost.
Ownership: every value has exactly one owner. When the owner falls out of scope, the value is dropped (freed). Double-free, gone. Leaks get much rarer but stay possible: an Rc cycle never drops, and mem::forget or Box::leak skip the free on purpose, because Rust counts a leak as safe.
Borrowing: code can create references (borrows) to values. The borrow checker holds the line on two rules: you can have either one mutable reference OR any number of immutable references, never both, and references can't outlive the data they refer to.
fn main() { let s = String::from("hello"); let r = &s; // immutable borrow - ok println!("{}", r); // use the borrow - ok drop(s); // ERROR: cannot drop s while r exists}These rules kill use-after-free (references can't outlive their data), data races (no simultaneous mutable access), and dangling pointers. Buffer overflows are caught by bounds checking on every array/slice access — the check gets optimised away when the compiler can prove it's redundant.
Rust's unsafe keyword unlocks the door for low-level work — raw pointer manipulation, FFI — that the borrow checker would otherwise refuse. Unsafe code is on the programmer to verify, but it's clearly marked and localised. Compare that to C/C++, where every line is implicitly unsafe.
Rust's safety guarantees only apply to safe Rust code. The unsafe keyword unlocks five capabilities: dereferencing raw pointers, calling unsafe functions, accessing mutable statics, implementing unsafe traits, and accessing union fields. Bugs in unsafe blocks can cause the same memory errors as C/C++. The key insight is that unsafe code is encapsulated: a well-written unsafe block presents a safe interface to the rest of the program, so bugs are localized to the unsafe code rather than potentially anywhere in the program.
Java and C#: Garbage Collection and Managed Memory
Java and C# lean on garbage collection to manage memory automatically and enforce memory safety through the runtime:
- No manual free: the GC reclaims unreachable objects automatically. Double-free and use-after-free can't happen — the programmer never explicitly frees memory.
- Bounds checking: every array access is checked at runtime.
ArrayIndexOutOfBoundsExceptionstands in for buffer overflow. - No pointer arithmetic: references are opaque handles, not raw addresses. You can't increment a reference to read adjacent memory.
- Type safety: the runtime enforces valid casts.
ClassCastExceptionstands in for type confusion. - Null safety: null pointer dereference raises
NullPointerExceptioninstead of triggering undefined behaviour (though it's still a frequent bug).
The trade-off is performance. GC pauses inject latency, bounds checks tax every array access, and the lack of direct memory control caps optimisation potential. For most application-level code that's a fine deal. For systems programming, the leash is too short.
Swift: Automatic Reference Counting
Swift relies on Automatic Reference Counting (ARC) — the compiler inserts retain (increment refcount) and release (decrement refcount) calls automatically. When an object's refcount hits zero, it's deallocated immediately, like a C++ destructor.
Swift heads off common errors with:
- No dangling pointers: ARC frees objects only when no strong references remain.
- Optional types: instead of null pointers, Swift uses
Optional<T>and forces explicit handling of the absent case. - Bounds checking: arrays are bounds-checked at runtime.
Swift's soft spot is reference cycles. Two objects pointing at each other never get to refcount zero. The programmer breaks cycles with weak or unowned references — a manual chore that, when forgotten, leaks memory.
Comparing Safety Guarantees
| Feature | C/C++ | Rust | Java/C# | Swift |
|---|---|---|---|---|
| Buffer overflow | Possible | Prevented (bounds check) | Prevented (bounds check) | Prevented (bounds check) |
| Use-after-free | Possible | Prevented (borrow checker) | Impossible (GC) | Prevented (ARC) |
| Double-free | Possible | Prevented (ownership) | Impossible (GC) | Prevented (ARC) |
| Memory leaks | Possible | Possible (rare) | Possible (rare) | Possible (cycles) |
| Data races | Possible | Prevented (borrow checker) | Possible | Possible |
| Runtime overhead | None | Minimal (bounds checks) | GC pauses, bounds checks | ARC overhead, bounds checks |
Performance Tradeoffs
Rust aims for C-level performance with safety. Its abstractions are zero-cost, and the borrow checker's constraints tend to nudge programmers toward cache-friendly, efficient designs. Bounds checks are the main runtime cost, and the optimiser strips most of them out.
Java and C# have made huge gains in JIT compilation, narrowing the gap with native code on many workloads. The JIT can eliminate bounds checks through range analysis, inline virtual calls through speculative optimisation, and even erase GC overhead for short-lived objects via escape analysis. GC overhead and memory layout constraints (objects always heap-allocated, with headers) still make Java/C# measurably slower than Rust or optimised C for memory-intensive work.
The direction of travel is clear. New systems languages are chasing memory safety without garbage collection: Rust proves it at compile time, Vale checks generational references at run time, and Zig goes for less, with bounds and overflow checks in its safe build modes but no language-level guard against use-after-free. Meanwhile GC languages keep tuning their runtimes to minimise the safety overhead. The era of accepting memory unsafety as the price of performance is winding down.