I'll show you several examples where Rust's memory safety features prevent common C vulnerabilities.
Example 1: Buffer Overflow
C Version (Vulnerable):
#include <stdio.h>
#include <string.h>
int main() {
char buffer[10];
char input[] = "This string is way too long for the buffer";
strcpy(buffer, input); // Buffer overflow!
printf("%s\n", buffer);
return 0;
}
Rust Version (Safe):
fn main() {
let mut buffer = [0u8; 10];
let input = b"This string is way too long for the buffer";
// This won't compile - Rust prevents the overflow at compile time
// buffer.copy_from_slice(input); // Compile error!
// Safe alternative - only copy what fits
let copy_len = std::cmp::min(buffer.len(), input.len());
buffer[..copy_len].copy_from_slice(&input[..copy_len]);
println!("{:?}", buffer);
}
Why Rust is safer: C's strcpy blindly copies data without bounds checking, allowing attackers to overwrite adjacent memory. Rust's array operations are bounds-checked at compile time or runtime, making buffer overflows impossible.
Example 2: Use After Free
C Version (Vulnerable):
#include <stdio.h>
#include <stdlib.h>
int main() {
int* ptr = malloc(sizeof(int));
*ptr = 42;
free(ptr);
printf("%d\n", *ptr); // Use after free - undefined behavior!
return 0;
}
Rust Version (Safe):
fn main() {
let ptr = Box::new(42);
drop(ptr); // Explicitly free the memory
// println!("{}", ptr); // Compile error! Can't use moved value
// The compiler prevents use-after-free at compile time
}
Why Rust is safer: Rust's ownership system tracks when values are moved or dropped. Once ptr is dropped, the compiler prevents any further access to it. C has no such protection, leading to crashes or security vulnerabilities.
Example 3: Double Free
C Version (Vulnerable):
#include <stdio.h>
#include <stdlib.h>
int main() {
int* ptr = malloc(sizeof(int));
*ptr = 42;
free(ptr);
free(ptr); // Double free - undefined behavior!
return 0;
}
Rust Version (Safe):
fn main() {
let ptr = Box::new(42);
drop(ptr);
// drop(ptr); // Compile error! Can't use moved value
// Rust prevents double-free at compile time
}
Why Rust is safer: After the first drop(), Rust considers ptr moved and unusable. Any attempt to drop it again results in a compile error, preventing double-free vulnerabilities that can lead to heap corruption.
Example 4: Null Pointer Dereference
C Version (Vulnerable):
#include <stdio.h>
#include <stdlib.h>
int* find_value(int* array, int size, int target) {
for (int i = 0; i < size; i++) {
if (array[i] == target) {
return &array[i];
}
}
return NULL; // Not found
}
int main() {
int numbers[] = {1, 2, 3, 4, 5};
int* result = find_value(numbers, 5, 10);
printf("Found: %d\n", *result); // Null pointer dereference!
return 0;
}
Rust Version (Safe):
fn find_value(array: &[i32], target: i32) -> Option<&i32> {
for item in array {
if *item == target {
return Some(item);
}
}
None // Not found
}
fn main() {
let numbers = [1, 2, 3, 4, 5];
let result = find_value(&numbers, 10);
match result {
Some(value) => println!("Found: {}", value),
None => println!("Not found"),
}
// Or using unwrap (which would panic safely if None):
// println!("Found: {}", result.unwrap());
}
Why Rust is safer: Rust's Option<T> type forces you to handle the possibility of null values explicitly. You cannot accidentally dereference a null pointer because the compiler requires you to check if the value exists first.
Example 5: Data Race in Multithreading
C Version (Vulnerable):
#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
int counter = 0;
void* increment(void* arg) {
for (int i = 0; i < 1000000; i++) {
counter++; // Race condition!
}
return NULL;
}
int main() {
pthread_t thread1, thread2;
pthread_create(&thread1, NULL, increment, NULL);
pthread_create(&thread2, NULL, increment, NULL);
pthread_join(thread1, NULL);
pthread_join(thread2, NULL);
printf("Counter: %d\n", counter); // Unpredictable result
return 0;
}
Rust Version (Safe):
use std::sync::{Arc, Mutex};
use std::thread;
fn main() {
let counter = Arc::new(Mutex::new(0));
let mut handles = vec![];
for _ in 0..2 {
let counter = Arc::clone(&counter);
let handle = thread::spawn(move || {
for _ in 0..1000000 {
let mut num = counter.lock().unwrap();
*num += 1;
}
});
handles.push(handle);
}
for handle in handles {
handle.join().unwrap();
}
println!("Counter: {}", *counter.lock().unwrap());
}
Why Rust is safer: Rust's type system prevents data races at compile time. You cannot share mutable data between threads without proper synchronization primitives like Mutex. The compiler enforces that shared data is properly protected, eliminating race conditions.
Key Memory Safety Mechanisms in Rust:
- Ownership System: Each value has exactly one owner, preventing use-after-free and double-free
- Borrowing Rules: References are checked at compile time to prevent dangling pointers
- Bounds Checking: Array and slice access is always bounds-checked
- No Null Pointers:
Option<T> forces explicit handling of potentially absent values
- Thread Safety: The type system prevents data races by requiring proper synchronization
These examples show how Rust's compile-time checks catch memory safety issues that would cause crashes, security vulnerabilities, or unpredictable behavior in C programs.