Introduction to Unsafe Rust
Rust's safety guarantees are one of its strongest features, but sometimes you need to break these rules to achieve low-level control, interface with hardware, or optimize critical code paths. The unsafe keyword gives you this power, but with great power comes great responsibility.
1. Understanding Raw Pointers
Raw pointers are Rust's equivalent to C pointers. Unlike references, they:
- Can be null
- Don't guarantee they point to valid memory
- Don't have automatic cleanup
- Can alias (multiple pointers to same memory)
- Don't enforce borrowing rules
fn main() {
let mut num = 42;
// Immutable raw pointer (*const T)
let r1 = &num as *const i32;
// Mutable raw pointer (*mut T)
let r2 = &mut num as *mut i32;
// Creating from arbitrary memory address (dangerous!)
let address = 0x012345usize;
let r3 = address as *const i32;
println!("Pointers created: {:p}, {:p}, {:p}", r1, r2, r3);
}
Dereferencing Raw Pointers
fn main() {
let mut num = 42;
let r1 = &num as *const i32;
let r2 = &mut num as *mut i32;
unsafe {
// Reading through immutable pointer
println!("r1 points to: {}", *r1);
// Writing through mutable pointer
*r2 = 100;
println!("r2 changed value to: {}", *r2);
}
println!("Final value: {}", num); // 100
}
2. Unsafe Functions and Blocks
Unsafe functions must be called from within unsafe blocks or other unsafe functions. This creates a clear boundary showing where unsafe operations occur.
unsafe fn dangerous() {
println!("Doing something dangerous!");
}
fn main() {
// This won't compile without unsafe block
// dangerous();
unsafe {
dangerous();
}
}
// Unsafe function that manipulates raw pointers
unsafe fn write_at_offset(ptr: *mut i32, offset: isize, value: i32) {
*ptr.offset(offset) = value;
}
fn main_example() {
let mut arr = [1, 2, 3, 4, 5];
let ptr = arr.as_mut_ptr();
unsafe {
// Write 100 at index 2
write_at_offset(ptr, 2, 100);
}
println!("Array: {:?}", arr); // [1, 2, 100, 4, 5]
}
Creating Safe Abstractions
The best practice is to wrap unsafe code in safe functions that maintain Rust's invariants:
use std::slice;
// Safe function using unsafe internally
fn split_at_mut_custom(slice: &mut [T], mid: usize) -> (&mut [T], &mut [T]) {
let len = slice.len();
let ptr = slice.as_mut_ptr();
// Validate preconditions
assert!(mid <= len);
unsafe {
(
slice::from_raw_parts_mut(ptr, mid),
slice::from_raw_parts_mut(ptr.add(mid), len - mid),
)
}
}
fn main() {
let mut v = vec![1, 2, 3, 4, 5, 6];
let (left, right) = split_at_mut_custom(&mut v, 3);
left[0] = 10;
right[0] = 20;
println!("{:?}", v); // [10, 2, 3, 20, 5, 6]
}
3. Calling External C Functions (FFI Preview)
One of the most common uses of unsafe is calling C functions through FFI:
extern "C" {
fn abs(input: i32) -> i32;
}
fn main() {
unsafe {
println!("Absolute value of -3 according to C: {}", abs(-3));
}
}
// More complex example: malloc and free
use std::alloc::{alloc, dealloc, Layout};
fn manual_allocation() {
unsafe {
// Allocate memory for i32
let layout = Layout::new::();
let ptr = alloc(layout) as *mut i32;
if ptr.is_null() {
panic!("Allocation failed!");
}
// Use the memory
*ptr = 42;
println!("Value: {}", *ptr);
// Must manually free!
dealloc(ptr as *mut u8, layout);
}
}
4. Implementing Unsafe Traits
Some traits are marked as unsafe because implementers must uphold certain invariants:
// Send trait indicates type can be transferred between threads
// Sync trait indicates type can be shared between threads
struct MyType {
data: *mut i32,
}
// We must guarantee this type is safe to send between threads
unsafe impl Send for MyType {}
// For mutable statics, we use unsafe
static mut COUNTER: u32 = 0;
fn increment_counter() {
unsafe {
COUNTER += 1;
}
}
// Better alternative: use std::sync::atomic
use std::sync::atomic::{AtomicU32, Ordering};
static ATOMIC_COUNTER: AtomicU32 = AtomicU32::new(0);
fn increment_atomic() {
ATOMIC_COUNTER.fetch_add(1, Ordering::SeqCst);
}
5. Practical Example: Ring Buffer
Let's build a lock-free ring buffer using unsafe code for performance:
use std::sync::atomic::{AtomicUsize, Ordering};
use std::alloc::{alloc, dealloc, Layout};
use std::ptr;
pub struct RingBuffer {
buffer: *mut T,
capacity: usize,
head: AtomicUsize,
tail: AtomicUsize,
}
impl RingBuffer {
pub fn new(capacity: usize) -> Self {
assert!(capacity > 0 && capacity.is_power_of_two());
let layout = Layout::array::(capacity).unwrap();
let buffer = unsafe {
alloc(layout) as *mut T
};
if buffer.is_null() {
panic!("Allocation failed");
}
RingBuffer {
buffer,
capacity,
head: AtomicUsize::new(0),
tail: AtomicUsize::new(0),
}
}
pub fn push(&self, value: T) -> Result<(), T> {
let head = self.head.load(Ordering::Acquire);
let tail = self.tail.load(Ordering::Acquire);
let next_tail = (tail + 1) & (self.capacity - 1);
if next_tail == head {
return Err(value); // Buffer full
}
unsafe {
ptr::write(self.buffer.add(tail), value);
}
self.tail.store(next_tail, Ordering::Release);
Ok(())
}
pub fn pop(&self) -> Option {
let head = self.head.load(Ordering::Acquire);
let tail = self.tail.load(Ordering::Acquire);
if head == tail {
return None; // Buffer empty
}
let value = unsafe {
ptr::read(self.buffer.add(head))
};
let next_head = (head + 1) & (self.capacity - 1);
self.head.store(next_head, Ordering::Release);
Some(value)
}
}
unsafe impl Send for RingBuffer {}
unsafe impl Sync for RingBuffer {}
impl Drop for RingBuffer {
fn drop(&mut self) {
// Drop all remaining elements
while self.pop().is_some() {}
// Deallocate buffer
let layout = Layout::array::(self.capacity).unwrap();
unsafe {
dealloc(self.buffer as *mut u8, layout);
}
}
}
fn main() {
let buffer = RingBuffer::new(8);
buffer.push(1).unwrap();
buffer.push(2).unwrap();
buffer.push(3).unwrap();
println!("{:?}", buffer.pop()); // Some(1)
println!("{:?}", buffer.pop()); // Some(2)
buffer.push(4).unwrap();
println!("{:?}", buffer.pop()); // Some(3)
println!("{:?}", buffer.pop()); // Some(4)
println!("{:?}", buffer.pop()); // None
}
6. Best Practices
🔑 Key Principles for Safe Unsafe Code
- Minimize Unsafe Code: Use unsafe only when absolutely necessary
- Encapsulate: Wrap unsafe code in safe abstractions
- Document Invariants: Clearly state what invariants must be maintained
- Validate Inputs: Check preconditions before unsafe operations
- Test Thoroughly: Use tools like Miri and extensive testing
- Review Carefully: Have unsafe code reviewed by experienced developers
/// Splits a mutable slice into two at the given index.
///
/// # Safety
///
/// Caller must ensure that `mid <= slice.len()`.
/// Violating this invariant leads to undefined behavior.
///
/// # Panics
///
/// Panics if `mid > slice.len()`.
pub fn split_at_mut_unsafe(
slice: &mut [T],
mid: usize
) -> (&mut [T], &mut [T]) {
let len = slice.len();
let ptr = slice.as_mut_ptr();
assert!(mid <= len, "mid must be <= len");
unsafe {
(
std::slice::from_raw_parts_mut(ptr, mid),
std::slice::from_raw_parts_mut(ptr.add(mid), len - mid),
)
}
}
7. Common Pitfalls
| Pitfall | Description | Solution |
|---|---|---|
| Null Pointer Dereference | Dereferencing a null pointer | Always check is_null() before dereferencing |
| Use After Free | Using memory after it's been deallocated | Track ownership carefully, use RAII patterns |
| Data Races | Concurrent access without synchronization | Use atomic operations or locks |
| Buffer Overflow | Writing past allocated memory | Validate bounds before pointer arithmetic |
| Alignment Issues | Accessing unaligned memory | Use std::ptr::read_unaligned |
Summary
✅ You've learned:
- How to create and use raw pointers safely
- When and how to use unsafe blocks and functions
- How to build safe abstractions around unsafe code
- Common patterns and pitfalls in unsafe Rust
- Best practices for writing maintainable unsafe code
Unsafe Rust is a powerful tool that enables low-level programming and performance optimization. By understanding its principles and following best practices, you can harness this power while maintaining code safety and correctness.