Skip to main content
Be Bitwise
RustAdvanced Rust Patterns

Unsafe Rust

Safe Rust shuts down whole classes of bugs before your program ever runs. Some operations though — dereferencing raw pointers, calling into C, hand-rolling certain data structures — sit beyond what the compiler can prove. unsafe opens that door, and tags every line that needs a closer human read.

What unsafe Unlocks

An unsafe block grants exactly five superpowers:

  1. Dereference raw pointers
  2. Call unsafe functions or methods
  3. Access or modify mutable static variables
  4. Implement unsafe traits
  5. Access fields of unions
rust
fn main() {
let mut x = 42;
let r1 = &x as *const i32; // Create raw pointer (safe)
let r2 = &mut x as *mut i32; // Create raw pointer (safe)
unsafe {
println!("r1 = {}", *r1); // Dereference (unsafe)
*r2 = 100; // Write through raw pointer (unsafe)
println!("r2 = {}", *r2);
}
}
Key Concept

unsafe doesn't switch off the borrow checker. It doesn't disable any of Rust's safety guarantees. It only unlocks those five operations — every other rule still applies. Get it wrong and you've got undefined behaviour, same as in C.

Raw Pointers

Raw pointers behave like C pointers — no lifetime tracking, no aliasing checks, no null guarantees:

rust
fn main() {
// Create from references
let x = 42;
let ptr: *const i32 = &x;
// Create from arbitrary address (DANGEROUS)
let addr = 0x012345usize;
let _ptr = addr as *const i32;
// Null pointer
let null: *const i32 = std::ptr::null();
// Pointer arithmetic
let arr = [1, 2, 3, 4, 5];
let ptr = arr.as_ptr();
unsafe {
let third = *ptr.add(2);
println!("Third element: {}", third); // 3
}
}

Calling C Functions (FFI)

Rust talks to C via FFI (the Foreign Function Interface):

rust
extern "C" {
fn abs(input: i32) -> i32;
fn strlen(s: *const std::os::raw::c_char) -> usize;
}
fn main() {
unsafe {
println!("abs(-5) = {}", abs(-5));
let s = std::ffi::CString::new("hello").unwrap();
println!("strlen = {}", strlen(s.as_ptr()));
}
}

Every extern call is unsafe — the compiler has no way to vouch that the C side honours Rust's invariants.

On edition 2024 the block itself has to be written unsafe extern "C" { ... }, an acknowledgement that the signatures you declare are a promise the compiler takes on trust. That syntax arrived in Rust 1.82; the plain extern "C" form above is the edition 2015 to 2021 spelling. Edition 2024 also turns the static_mut_refs lint into an error by default, so taking & or &mut to a static mut is refused; reach for &raw const/&raw mut, an atomic, or a Mutex instead.

Safe Abstractions over Unsafe Code

The golden rule: wrap unsafe code in a safe API. The internals can rummage around with raw pointers all they like, as long as the public surface stays sound:

rust
pub struct SafeVec<T> {
ptr: *mut T,
len: usize,
capacity: usize,
}
impl<T> SafeVec<T> {
pub fn new() -> Self {
SafeVec {
ptr: std::ptr::null_mut(),
len: 0,
capacity: 0,
}
}
pub fn push(&mut self, value: T) {
if self.len == self.capacity {
self.grow();
}
unsafe {
self.ptr.add(self.len).write(value);
}
self.len += 1;
}
pub fn get(&self, index: usize) -> Option<&T> {
if index < self.len {
unsafe { Some(&*self.ptr.add(index)) }
} else {
None
}
}
fn grow(&mut self) {
let new_capacity = if self.capacity == 0 { 4 } else { self.capacity * 2 };
let new_layout = std::alloc::Layout::array::<T>(new_capacity).unwrap();
let new_ptr = unsafe { std::alloc::alloc(new_layout) as *mut T };
if new_ptr.is_null() {
std::alloc::handle_alloc_error(new_layout);
}
if self.len > 0 {
unsafe {
std::ptr::copy_nonoverlapping(self.ptr, new_ptr, self.len);
}
if self.capacity > 0 {
let old_layout = std::alloc::Layout::array::<T>(self.capacity).unwrap();
unsafe { std::alloc::dealloc(self.ptr as *mut u8, old_layout); }
}
}
self.ptr = new_ptr;
self.capacity = new_capacity;
}
}
impl<T> Drop for SafeVec<T> {
fn drop(&mut self) {
if self.capacity > 0 {
// Drop all elements
for i in 0..self.len {
unsafe { std::ptr::drop_in_place(self.ptr.add(i)); }
}
let layout = std::alloc::Layout::array::<T>(self.capacity).unwrap();
unsafe { std::alloc::dealloc(self.ptr as *mut u8, layout); }
}
}
}

Here's SafeVec on the bench, holding a type that announces its own destruction so you can count the drops. Layout::array is swapped for a small helper, because the runner's Rust 1.40 is older than it.

Try itPush a fifth name to force grow() to reallocate, then check every element is still dropped exactly once.
Rust (1.40.0)
SafeVec still has a hole. Try SafeVec<()>: what does grow() ask the allocator for?

A block of zero bytes. () has size 0, so the layout's size is 0, and the GlobalAlloc::alloc docs say plainly that calling it with a zero-size layout is undefined behaviour. The program may well appear to work, which is the worst way for UB to show up. std::vec::Vec never allocates for zero-sized types at all; a sound SafeVec has to special-case them the same way.

That's the loudest gap, not the only one. Treat SafeVec as a teaching sketch and compare it with the real Vec:

  • No PhantomData<T>. A bare *mut T doesn't tell the compiler that SafeVec<T> owns T values and drops them. Vec holds its pointer through a type that carries PhantomData<T>, which is what lets the drop checker reason about borrowed data inside the elements.
  • Growth arithmetic. capacity * 2 and the layout size should both be checked (checked_mul), with overflow turned into a clean panic. The runner's layout_for does that for the size; Layout::array returns an Err the code above simply unwraps.
  • Send and Sync. Because of the raw pointer, SafeVec is neither, so you can't move one to another thread. That's sound but limiting; Vec<T> is Send when T is, through an unsafe impl someone had to justify.

What Undefined Behaviour Looks Like

"UB" is abstract until you see the shapes it takes. Each of these compiles inside unsafe and is still forbidden:

  • Invalid values: a bool holding 2, an enum with a discriminant that isn't one of its variants, a char above 0x10FFFF, or a null reference. Even creating one is UB, before anything reads it.
  • Uninitialised reads: reading an integer from MaybeUninit::uninit() or from freshly allocated memory.
  • Aliasing violations: a &mut T existing at the same time as any other reference to the same T, or writing through a pointer derived from a &T.
  • Dangling or misaligned access: use-after-free, out-of-bounds pointer arithmetic, or reading a u64 from an odd address.
  • Data races: two threads touching the same location without synchronisation, at least one of them writing.

The compiler optimises on the assumption that none of these ever happen, which is why the symptoms tend to show up far from the cause.

Unsafe Traits

An unsafe trait shifts responsibility to the implementor — invariants the compiler can't verify itself:

rust
// Send: safe to transfer between threads
// Sync: safe to reference from multiple threads
// Both are unsafe traits - implementing them incorrectly causes data races
unsafe impl Send for MyType {}
unsafe impl Sync for MyType {}

Most types pick up Send and Sync automatically. Manual impls only come up around raw pointers or FFI handles.

Common Unsafe Patterns

Splitting a mutable slice:

rust
fn split_at_mut(slice: &mut [i32], mid: usize) -> (&mut [i32], &mut [i32]) {
let len = slice.len();
let ptr = slice.as_mut_ptr();
assert!(mid <= len);
unsafe {
(
std::slice::from_raw_parts_mut(ptr, mid),
std::slice::from_raw_parts_mut(ptr.add(mid), len - mid),
)
}
}

The borrow checker can't prove the two halves are disjoint, but we know they are — the split index does the work the type system won't.

Guidelines for Using unsafe

  1. Minimize unsafe blocks - make them as small as possible
  2. Document invariants - explain why each unsafe operation is sound
  3. Encapsulate - expose a safe public API
  4. Test thoroughly - use miri and sanitizers
  5. Question necessity - can you achieve this with safe Rust?
rust
// GOOD: documented unsafe
/// # Safety
/// `ptr` must be valid and properly aligned.
/// The memory at `ptr` must contain a valid `T`.
unsafe fn read_value<T>(ptr: *const T) -> T {
ptr.read()
}

Using miri to Validate Unsafe Code

miri is an interpreter that sniffs out undefined behaviour in unsafe Rust:

bash
cargo +nightly miri test

miri catches use-after-free, out-of-bounds access, misalignment, data races, and a long tail of other UB. If you're shipping unsafe, miri belongs in your CI.