Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

Rust Unsafe: Raw Pointers, FFI Bindings, and Soundness Invariants

What unsafe actually unlocks, the five soundness contracts behind raw pointers, and the FFI rules for repr(C), CString and unwinding.

~4 min readRust
#Rust#Unsafe#FFI
3D illustration of safe abstraction shields wrapping an isolated unsafe FFI boundary

Quick Summary

unsafe does not turn off the borrow checker or the type system. It unlocks exactly five abilities: dereference a raw pointer, call an unsafe fn, access a mutable static item, implement an unsafe trait, and access the fields of a union. Everything else — ownership, lifetimes, type checking — applies unchanged.

The point of an unsafe block is a promise. The compiler cannot verify that you uphold the invariants of the operation, so it asks you to assert them, and the safety of the whole program then rests on that assertion. That is why the required practice is a // SAFETY: comment stating the invariant and the reason it holds, and why a safe wrapper around unsafe code is only worth publishing when the invariant is enforced by its constructor rather than documented in prose.

FFI is the main practical use: calling C functions, exposing Rust functions to C, and reading buffers whose length is known only from the C side. The rules there are narrow and mechanical — #[repr(C)] for shared structs, CString/CStr for strings, explicit null checks, and no unwinding across the boundary.

Basic Syntax & Signature

rust
use std::ptr; use std::ffi::{CStr, CString}; use std::os::raw::{c_char, c_int}; // Raw pointers: creation is safe, dereferencing is not. fn raw_basics() { let mut value = 42i32; let p: *const i32 = &value; let m: *mut i32 = &mut value; // SAFETY: both pointers came from a live local and are properly aligned. unsafe { assert_eq!(*p, 42); *m = 7; assert_eq!(*p, 7); } assert_eq!(value, 7); } // An unsafe fn carries a contract the caller must uphold. /// # Safety /// `src` must point to `len` consecutive, initialized, aligned `u8` values /// belonging to a single allocation that stays alive for `'a`. unsafe fn as_bytes<'a>(src: *const u8, len: usize) -> &'a [u8] { // SAFETY: guaranteed by the caller contract above. unsafe { std::slice::from_raw_parts(src, len) } } // FFI: C ABI, no name mangling, C layout. #[repr(C)] pub struct Point { pub x: c_int, pub y: c_int } #[unsafe(no_mangle)] pub extern "C" fn point_len(p: *const Point) -> c_int { if p.is_null() { return 0; } // SAFETY: null checked; C side promises a valid Point. let p = unsafe { &*p }; p.x + p.y } extern "C" { fn abs(input: c_int) -> c_int; } fn main() { raw_basics(); let data = [1u8, 2, 3]; // SAFETY: the array is alive and has exactly 3 initialized bytes. let slice = unsafe { as_bytes(data.as_ptr(), data.len()) }; assert_eq!(slice, [1, 2, 3]); let p = Point { x: 3, y: 4 }; assert_eq!(point_len(&p), 7); // SAFETY: abs() is a C function with no side effects on Rust state. assert_eq!(unsafe { abs(-5) }, 5); // C strings: null-terminated, owned buffer on the Rust side. let owned = CString::new("hello").unwrap(); let borrowed: &CStr = owned.as_c_str(); assert_eq!(borrowed.to_str().unwrap(), "hello"); let raw: *const c_char = owned.as_ptr(); // SAFETY: the pointer is valid while `owned` is alive. assert_eq!(unsafe { CStr::from_ptr(raw) }, borrowed); }

Edition note: in Rust 2024, unsafe fn bodies are no longer implicitly unsafe (the unsafe_op_in_unsafe_fn lint is on), so every unsafe operation inside needs its own unsafe {} block. extern blocks and attributes that affect linkage also take the unsafe keyword: #[unsafe(no_mangle)], #[unsafe(export_name = "...")], and unsafe extern "C" { ... }.

Key Comparison Table

OperationSafe or unsafeInvariant the programmer must guarantee
Create *const T / *mut TSafeNone at creation
Dereference a raw pointerUnsafeNon-null, aligned, initialized, live, not aliased against a &mut
slice::from_raw_partsUnsafeSingle allocation, len * size_of::<T>() <= isize::MAX, all elements initialized
ptr::read / ptr::writeUnsafeValid for reads/writes; double-free if read is repeated on owned data
MaybeUninit::assume_initUnsafeValue was actually initialized, including padding rules for some types
transmuteUnsafeSame size, and the target bit pattern is a valid value
impl Send / impl SyncUnsafe traitNo data races are possible through the type
static mut accessUnsafeNo concurrent access, no aliasing violation
set_var (edition 2024)UnsafeNo other thread reads the environment concurrently
Call an unsafe fnUnsafeEverything in its # Safety section
FFI directionType mappingOwnership rule
Rust receives *const c_charCStr::from_ptrBorrowed; do not free
Rust sends &strCString::into_rawC must call the matching free function
C struct in Rust#[repr(C)] structField order and padding match C
Rust callback to Cextern "C" fnMust not unwind; catch panics at the boundary
C-allocated buffer*mut u8 + lengthRust must not free with the wrong allocator

Practical Edge Cases & Deep Dives

1. A safe wrapper that keeps the invariant in the constructor

rust
pub struct FixedBuffer<const N: usize> { data: [u8; N], len: usize, } impl<const N: usize> FixedBuffer<N> { pub fn new() -> Self { FixedBuffer { data: [0; N], len: 0 } } pub fn push(&mut self, byte: u8) -> bool { if self.len >= N { return false; } self.data[self.len] = byte; self.len += 1; true } pub fn as_slice(&self) -> &[u8] { // SAFETY: `len` is only incremented after a successful write, so // data[..len] is always initialized, and len <= N. unsafe { self.data.get_unchecked(..self.len) } } } fn main() { let mut b = FixedBuffer::<4>::new(); assert!(b.push(1)); assert!(b.push(2)); assert_eq!(b.as_slice(), [1, 2]); }

get_unchecked skips a bounds check the compiler already knows how to remove in this shape (the slice is short and the loop bound is provable), so the realistic version of this code uses &self.data[..self.len]. The structural point matters more than the micro-optimization: as_slice is safe to call because push is the only writer and it maintains len <= N and initialization.

2. MaybeUninit for a partially initialized array

rust
use std::mem::MaybeUninit; fn read_into(buf: &mut [MaybeUninit<u8>], src: &[u8]) -> &[u8] { let n = buf.len().min(src.len()); for (slot, &byte) in buf.iter_mut().zip(src).take(n) { slot.write(byte); } // SAFETY: exactly the first n slots were written above. unsafe { std::slice::from_raw_parts(buf.as_ptr() as *const u8, n) } } fn main() { let mut buf: [MaybeUninit<u8>; 8] = [MaybeUninit::uninit(); 8]; assert_eq!(read_into(&mut buf, b"abc"), b"abc"); }

MaybeUninit exists because [0u8; N] is not a valid initial state for every type — a zeroed &T or Box<T> is immediate undefined behaviour. The rule is to track how many slots were initialized outside the buffer and never expose the whole array before every element is written.

3. Raw pointer projection without creating a reference

rust
#[repr(C)] struct Header { kind: u8, len: u32 } fn kind_of(ptr: *const Header) -> Option<u8> { if ptr.is_null() { return None; } // `addr_of!` avoids creating an intermediate reference, which matters // when the memory is not yet fully initialized or may be aliased. let kind = unsafe { std::ptr::addr_of!((*ptr).kind) }; // SAFETY: non-null and aligned; `kind` is the first field of a repr(C) // struct, so it is initialized if the C side filled the header. Some(unsafe { *kind }) } fn main() { let h = Header { kind: 7, len: 0 }; assert_eq!(kind_of(&h), Some(7)); assert_eq!(kind_of(std::ptr::null()), None); }

&(*ptr).field creates a reference to the whole struct before projecting; addr_of! computes the field address directly. In unaligned packet parsing or FFI structs with uninitialized padding, the difference between the two forms is the difference between sound and undefined behaviour.

4. Panics and unwinding across an FFI boundary

rust
use std::panic::{catch_unwind, AssertUnwindSafe}; #[unsafe(no_mangle)] pub extern "C" fn process(input: *const u8, len: usize) -> i32 { // A panic that escapes an `extern "C"` function aborts the process; // catch it at the boundary and translate to an error code. let result = catch_unwind(AssertUnwindSafe(|| { if input.is_null() { return -1; } // SAFETY: caller guarantees `len` valid bytes at `input`. let bytes = unsafe { std::slice::from_raw_parts(input, len) }; bytes.iter().map(|b| *b as i32).sum() })); match result { Ok(code) => code, Err(_) => -2, } }

Since Rust 1.81, unwinding out of an extern "C" function aborts rather than being undefined behaviour, but aborting a host process is still not an acceptable failure mode for a library. Returning a negative error code and logging the panic payload is the contract C callers can actually handle.

5. unsafe impl Send only when the data really is thread-safe

rust
use std::cell::UnsafeCell; use std::sync::atomic::{AtomicUsize, Ordering}; // A counter shared across threads. The atomic provides the synchronization // that makes the UnsafeCell inside it safe to share. struct AtomicCounter { count: AtomicUsize } impl AtomicCounter { fn new() -> Self { AtomicCounter { count: AtomicUsize::new(0) } } fn inc(&self) -> usize { self.count.fetch_add(1, Ordering::Relaxed) + 1 } } // SAFETY: all interior mutability goes through atomic operations, so there // is no data race; the type contains no references. unsafe impl Sync for AtomicCounter {} unsafe impl Send for AtomicCounter {} // The wrapper that is NOT safe to share: UnsafeCell alone has no atomics. struct CellCounter { count: UnsafeCell<usize> } impl CellCounter { fn new() -> Self { CellCounter { count: UnsafeCell::new(0) } } fn inc(&self) -> usize { // SAFETY: only sound when accessed from one thread; see the bound // in `spawn_one` below. unsafe { *self.count.get() += 1; *self.count.get() } } } fn spawn_one(counter: &CellCounter) -> usize { counter.inc() } fn main() { let c = AtomicCounter::new(); std::thread::scope(|s| { s.spawn(|| { c.inc(); }); s.spawn(|| { c.inc(); }); }); assert_eq!(c.count.load(Ordering::Relaxed), 2); let single = CellCounter::new(); assert_eq!(spawn_one(&single), 1); }

unsafe impl Sync is a claim that concurrent shared access cannot produce a data race. UnsafeCell alone makes a type !Sync precisely because it provides no such guarantee; asserting it without an atomic or a lock is how soundness bugs enter a codebase that otherwise uses no unsafe at the call site.

6. transmute alternatives that keep the code reviewable

rust
fn main() { // Prefer explicit conversions over transmute: same effect, no UB risk. let bytes = 0x0102_0304u32.to_ne_bytes(); let back = u32::from_ne_bytes(bytes); assert_eq!(back, 0x0102_0304u32); // A slice of u8 to a slice of u32 requires alignment, length divisibility, // and no aliasing; bytemuck expresses that safely. // let words: &[u32] = bytemuck::cast_slice(&bytes); assert_eq!(bytes.len(), 4); // transmute compiles only when sizes match; the compile check is not // a soundness check. // SAFETY: both are [u8; 4] and u32 with matching size and alignment. let n: u32 = unsafe { std::mem::transmute([1u8, 0, 0, 0]) }; assert_eq!(n, 1); }

transmute will happily turn a &'static str into an integer or a bool into 2, both of which are undefined behaviour. Use to_ne_bytes/from_ne_bytes for integers, bytemuck for validated slice casts, and #[repr(transparent)] newtypes for type-level reinterpretation.

Common Compilation/Runtime Mistakes

Error / symptomCauseFix
E0133: use of unsafe function requires unsafe blockunsafe fn body is not implicitly unsafe in edition 2024Wrap each operation in unsafe {}
E0658: unsafe attributeEdition 2024 requires #[unsafe(no_mangle)]Add the unsafe(...) wrapper
undefined behaviour under Miri on &*ptrPointer not aligned or danglingUse read_unaligned, addr_of!, or fix the lifetime
SIGSEGV in an FFI callNull or freed pointer passed to CCheck is_null(), keep the owner alive
abort when a panic crosses extern "C"Unwinding into Ccatch_unwind at the boundary
E0277: ... cannot be shared between threads safely after unsafe implThe type still is not Sync for a real reasonAdd a lock or atomic, do not silence it
transmute yields nonsense for bool or charInvalid bit patternValidate with try_from or bytemuck
Double free after CString::into_rawC freed with free instead of the matching functionProvide a free_* function in the same library
E0133 inside static mut accessstatic mut access is unsafeAtomicUsize, or OnceLock
Data race reported by ThreadSanitizer, none by borrowckUnsafe code defeated the aliasing rulesModel the access with UnsafeCell plus atomics

The habit that keeps unsafe code reviewable: one unsafe block per invariant, with a // SAFETY: comment naming the invariant and why the surrounding code establishes it. Clippy's undocumented_unsafe_blocks lint enforces exactly that, and running cargo +nightly miri test on the module catches the aliasing violations that tests written in safe code never exercise.

Try matching browser tools

All tools

Small utilities that fit Rust work — they run entirely in this browser tab, so nothing you paste leaves your device.

All Rust guides

More in Rust

All Rust guides

The guides filed next to this one in Rust, in library order.