Example 1: Buffer Overflow
C Code
#include <string.h>
#include <stdio.h>
int main() {
char buffer[5]; // Buffer can hold up to 5 characters (including null terminator)
strcpy(buffer, "Overflow!"); // "Overflow!" is 10 characters (including '\0')
printf("%s\n", buffer);
return 0;
}
Rust Equivalent
fn main() {
let mut buffer = ['\0'; 5]; // Fixed-size array of 5 characters
let s = "Overflow!"; // 10 characters
// Attempting to copy s into buffer would panic:
// buffer.copy_from_slice(s.as_bytes()); // Panics at runtime: "source slice length (10) exceeds destination (5)"
// Using a String with capacity checks:
let mut s = String::with_capacity(5);
s.push_str("Overflow!"); // Panics at runtime: "capacity exceeded"
}
Explanation
- C's Problem:
strcpy copies the entire string without checking the destination buffer's size. This overwrites memory beyond buffer, corrupting adjacent memory and causing undefined behavior.
- Rust's Solution:
- Fixed Arrays: Rust arrays (
['\0'; 5]) have a fixed size. Copying a larger slice into them requires explicit unsafe code or a runtime panic.
- String Type: Rust’s
String type enforces capacity checks. The push_str method panics if the string exceeds its capacity, preventing overflow.
- No Implicit Undefined Behavior: Rust avoids silent memory corruption by enforcing checks at runtime (or compile time for static checks).
Example 2: Dangling Pointers
C Code
#include <stdio.h>
char* get_buffer() {
char local[10] = "Hello"; // Local variable on the stack
return local; // Returns a pointer to a local variable
}
int main() {
char* p = get_buffer();
printf("%s", p); // Dangling pointer: local is deallocated after function exit
return 0;
}
Rust Equivalent
fn get_buffer() -> &'static str {
let local = String::from("Hello");
&local // Compiler error: `local` is dropped here while still borrowed
}
// To fix, return an owned value (e.g., String):
fn get_buffer_safe() -> String {
String::from("Hello")
}
fn main() {
let s = get_buffer_safe();
println!("{}", s); // Safe: `s` owns the data
}
Explanation
- C's Problem: Returning a pointer to a local variable (
local) creates a dangling pointer. The memory is freed when get_buffer exits, leading to undefined behavior.
- Rust's Solution:
- Lifetime Tracking: The Rust compiler ensures references (
&local) cannot outlive the variable they reference. The error occurs at compile time.
- Ownership Transfer: To return data safely,
get_buffer_safe returns an owned String, transferring ownership to the caller.
- No Dangling References: Rust’s ownership model enforces that references are valid for their entire lifetime, preventing dangling pointers.
Example 3: Double Free
C Code
#include <stdlib.h>
void dangerous() {
char* p = (char*)malloc(10);
free(p);
free(p); // Double-free: freeing already freed memory
}
Rust Equivalent
fn dangerous() {
let p = Box::new(0); // Allocate on the heap
drop(p); // Explicitly drop the Box
drop(p); // Compiler error: "use of moved value: `p`"
}
Explanation
- C's Problem: Freeing the same pointer twice (
free(p)) corrupts the heap and causes undefined behavior.
- Rust's Solution:
- Ownership Model:
Box<T> owns its data. Dropping p transfers ownership to the heap, invalidating p.
- Move Semantics: After
drop(p), p is considered "moved" and cannot be used again. The second drop(p) is a compile-time error.
- No Double Free: Rust ensures each value has a single owner, preventing accidental double frees.
Example 4: Use After Free
C Code
#include <stdio.h>
#include <stdlib.h>
void use_after_free() {
char* p = (char*)malloc(10);
free(p);
printf("%s", p); // Accessing freed memory
}
Rust Equivalent
fn use_after_free() {
let p = Box::new(0); // Heap allocation
drop(p); // Ownership is moved to the heap
println!("{}", p); // Compiler error: "use of moved value: `p`"
}
Explanation
- C's Problem: Accessing
p after free(p) reads/writes to deallocated memory, leading to undefined behavior.
- Rust's Solution:
- Ownership Transfer:
drop(p) moves ownership of p to the heap, invalidating the original variable.
- Compile-Time Safety: The Rust compiler prevents using
p after it has been moved, ensuring no use-after-free errors.
- No Undefined Behavior: Rust’s ownership and borrowing rules enforce that variables are valid only when they own their data.
Key Rust Features Enforcing Memory Safety:
-
Ownership and Borrowing:
- Each value has a single owner. When ownership is transferred (e.g.,
drop(p)), the original variable becomes invalid.
- Borrowing (
&) ensures references are immutable or mutable but never outlive their owner.
-
Lifetime Tracking:
- The compiler checks that references do not outlive the data they point to, preventing dangling pointers.
-
No Implicit Undefined Behavior:
- Rust enforces checks at compile time (e.g., invalid references) or runtime (e.g., buffer overflows), avoiding silent memory corruption.
-
No Manual Memory Management:
- Rust’s
Box, Vec, and String types automatically manage memory, with ownership rules ensuring safe allocation and deallocation.
By design, Rust eliminates entire classes of memory bugs (e.g., buffer overflows, dangling pointers) that are common in C, making it inherently more memory-safe.