Unsafe and FFI
The Rust compiler proves memory safety only for what it can check: references, ownership, lifetimes. But some necessary code does not fit those rules. Vec manages its heap buffer by hand, Mutex calls OS primitives, a driver writes to a physical address, and a C library takes a bare pointer. For such code there is unsafe: a block in which the programmer takes over a check the compiler cannot do.
unsafe does not switch off borrow checking or type checking. It opens exactly five capabilities: dereference a raw pointer, call an unsafe function, access a static mut, implement an unsafe trait, and read a union field. The price of a mistake inside the block is undefined behavior: the compiler optimizes the code on the assumption that it never happens, and the program may do anything at all. The Miri interpreter helps find such mistakes.
The core technique is not to smear unsafe across the code but to hide it inside a safe function or type for which no call from safe code can lead to undefined behavior. That is how Vec, String, split_at_mut and wrappers over C libraries are built. Code crosses the boundary with C through FFI: unsafe extern "C", CString and CStr, #[repr(C)]. In edition 2024 these places are marked explicitly: extern blocks and attributes such as no_mangle are written with unsafe too. This topic walks unsafe Rust layer by layer — from the five superpowers to safe wrappers.
Topic map
- unsafe Superpowers — the five operations
unsafeunlocks; borrow checking and type checking still run inside the block;unsafe fnversus anunsafeblock, the# Safetysection andunsafe_op_in_unsafe_fnin edition 2024. - Raw Pointers —
*const Tand*mut Twith no lifetime and no borrowing rules; creating one is safe, dereferencing only inunsafe;&raw constand&raw mut;ptr::null,add;static mutand the ban on references to it. - Undefined Behavior — dangling and misaligned pointers, data races, breaking the reference rules, invalid values such as a
boolequal to 2; why "it works for me" proves nothing; Miri and sanitizers. - FFI and C —
unsafe extern "C"andsafe fn;CString,CStrand thec"…"literal;#[repr(C)];#[unsafe(no_mangle)]; who frees memory at the boundary; a panic inextern "C"aborts the process; bindgen and cbindgen;no_std. - Safe Abstractions —
split_at_muton raw pointers; soundness of a wrapper;// SAFETY:comments and the# Safetysection; private fields as the boundary of an invariant; a hand-writtenunsafe impl Send.
Common mistakes and traps
| Mistake | Consequence |
|---|---|
Assuming unsafe switches off the borrow checker | Inside the block you still get error[E0502]: cannot borrow `s` as mutable because it is also borrowed as immutable |
Taking a reference to a static mut, including implicitly through println! | In edition 2024 that is error: creating a shared reference to mutable static; you need &raw const or &raw mut, or better an atomic or a Mutex |
Testing unsafe code by running it and deciding all is well | Undefined behavior may stay hidden in a debug build and break the release build or the next compiler version |
Writing CString::new(s).unwrap().as_ptr() on one line | The temporary CString is dropped at the end of the statement and the pointer dangles; the compiler warns this creates a dangling pointer |
| Freeing in C memory that Rust allocated, or the other way round | Different allocators: undefined behavior; the side that allocated must free |
Letting a panic escape an extern "C" function | The process aborts: panic in a function that cannot unwind |
Leaving an unsafe block without a // SAFETY: comment | A reviewer cannot check which invariants it assumes and who upholds them |
Why it matters in interviews
Unsafe Rust comes up for senior roles and wherever Rust meets C: systems programming, embedded, library bindings, high-performance data structures. The check is not whether you can write unsafe but whether you understand where the compiler's guarantees end and how to restore them by hand.
What interviewers usually check:
- What
unsafeallows and which checks it does not switch off. - How raw pointers differ from references, and why creating a pointer is safe but dereferencing it is not.
- What counts as undefined behavior in Rust and how to find it (Miri, sanitizers).
- How to call a C function and export your own:
unsafe extern "C",CString,#[repr(C)],#[unsafe(no_mangle)], who frees memory. - How to wrap
unsafecode in a safe interface and document its invariants. - When
SendorSyncis implemented by hand and what you promise by doing so.