skip to content

Unsafe Code and FFI

unsafe unlocks raw pointers and FFI, and the programmer, not the compiler, upholds the rules. Interviewers test what unsafe permits, undefined behaviour, C interop and sound abstractions.

on this pageshow

explore

questions

27

In Rust 2024, how do you declare and call a C function such as `strlen`, and why does the call need `unsafe`?

level: juniorimportance: must knowfreq 55%

answer

  1. a block of foreign signatures
  2. a keyword before extern
  3. rustc never sees the C body
  4. safe or unsafe per item

basics

~20 s

Declare the C signature inside an unsafe extern "C" block and call it inside an unsafe block: rustc cannot check foreign code, so the caller vouches for its preconditions. An item declared safe fn needs no unsafe block.

solid answer

~50 s

You write `unsafe extern "C" { fn strlen(s: *const c_char) -> usize; }` and the linker resolves `strlen` from the C library. The `unsafe` on the block is the author's promise that every signature matches the real C definition, because a wrong one is undefined behaviour that nothing checks; since the 2024 edition rustc rejects a block without it (`error: extern blocks must be unsafe`). Items in the block are unsafe to call by default, so `strlen(p)` goes inside an `unsafe { }` block where you uphold its contract: `p` is non-null and NUL-terminated. Since Rust 1.82 an item can be declared `safe fn` when no argument can make it misbehave, like `abs(c_int)`, and is then called like ordinary Rust. Parameter types come from `std::ffi` (`c_char`, `c_int`, `c_void`) so they match the platform's C types.

code

rust · 16 lines
rust
use std::ffi::{c_char, c_int, CStr};

unsafe extern "C" {
    // Any i32 is a valid input, so the declaration can promise safety.
    safe fn abs(x: c_int) -> c_int;
    // Needs a valid, NUL-terminated pointer: stays unsafe to call.
    fn strlen(s: *const c_char) -> usize;
}

fn main() {
    let n = abs(-7); // no unsafe block: declared `safe`
    let s: &CStr = c"compress";
    // SAFETY: `s` is a valid NUL-terminated string that outlives the call.
    let len = unsafe { strlen(s.as_ptr()) };
    println!("abs = {n}, strlen = {len}");
}

go deeper

for a junior

Recall the shape: signatures in an unsafe extern "C" block, calls inside an unsafe block, C types from std::ffi. Say plainly that rustc cannot see or check the C code.

for a middle

Explain the two promises: the block's author vouches for the signatures, the caller vouches for each call's preconditions. Know that items default to unsafe and that safe fn opts one out.

for a senior

Show that a mismatched signature links fine and is undefined behaviour, and that safe fn is only for functions no input can break. Keep raw declarations private behind safe wrappers that establish preconditions.

for a principal

Frame the declaration as an unchecked contract with another codebase. A team should keep that contract in one audited module, generated or checked against the real header, so it stays correct as the library changes.

## What an extern block declares Rust calls C through a **foreign function interface (FFI)**: Rust code calls a function that was compiled by a C compiler and lives in another object file or library. To do that, rustc needs a **declaration**: the function's name, its parameter and return types, and its **ABI** (application binary interface, the calling convention that says where arguments go in registers and on the stack). That declaration lives in an **extern block**: ```rust unsafe extern "C" { fn strlen(s: *const c_char) -> usize; } ``` - `"C"` is the ABI string. The Reference defines it as the default ABI of the dominant C compiler for the target. Leaving the string out also means `"C"`, but the Reference notes that form is being phased out, so write it. - The body holds declarations ending in semicolons, usually functions and sometimes statics. The code comes from whatever library the linker finds; how that library gets linked is a build-configuration matter, not something the block itself controls. - The name is matched by **symbol** at link time. Nothing compares your types with the C header. ## Why the block itself is unsafe Because rustc never sees the C definition, it cannot tell whether `strlen` really takes one pointer and returns a `size_t`. If you declare `fn strlen(s: *const c_char) -> u8` or forget a parameter, the program still compiles and links, and every call is **undefined behaviour**. The `unsafe` keyword in front of `extern` records who carries that risk: the author of the block promises the signatures are correct. The 2024 edition guide puts it the same way. The keyword stresses that the author of the extern block must make sure the signatures are correct. ## Calling: unsafe by default, safe by opt-in The Reference states that a function declared in an extern block is **implicitly unsafe** unless the `safe` qualifier is present. So there are two kinds of item: | Declared as | Call site | Use it when | |---|---|---| | `fn strlen(...)` or `unsafe fn strlen(...)` | inside `unsafe { }` | the C function has preconditions: valid pointers, lengths, initialised state | | `safe fn abs(x: c_int) -> c_int` | ordinary call | every value a safe caller can pass is fine | An unsafe call obliges the caller to meet the foreign function's contract. For `strlen`, the pointer must be non-null and point to a NUL-terminated string that stays alive for the call. The compiler enforces only the *location* of the call: without the block you get `` error[E0133]: call to unsafe function `strlen` is unsafe and requires unsafe block ``. By convention a `// SAFETY:` comment above the block says why the contract holds. Marking an item `safe` moves the proof to the declaration. It is right for `abs` or `sqrt`, wrong for anything that dereferences a pointer you pass. ## What changed, and when | Rust | `extern "C" { }` | `unsafe extern "C" { }` | `safe fn` items | |---|---|---|---| | Editions before 2024, before 1.82 | accepted | not available | not available | | Editions before 2024, 1.82 and later | accepted | accepted | only inside an `unsafe extern` block | | Edition 2024 (from 1.85) | **error**: `extern blocks must be unsafe` | required | allowed | On edition 2024, rustc 1.99 reports the old form as `error: extern blocks must be unsafe` with the help line `` needs `unsafe` before the extern keyword ``. On edition 2021, writing `safe fn` inside a plain `extern "C"` block is an error too: `` items in `extern` blocks without an `unsafe` qualifier cannot have safety qualifiers ``. ## Getting the signature right 1. **Use C types from `std::ffi`.** `c_int`, `c_long`, `c_char` and `c_void` follow the target's C definitions. Whether `c_char` is `i8` or `u8` depends on the platform, and `c_long` differs between 64-bit Windows and 64-bit Linux. 2. **Use raw pointers for C pointers.** `*const T` and `*mut T` say nothing about lifetimes or non-null-ness, which is the honest description of a C pointer. A reference in a foreign signature makes a promise you have to keep on C's behalf. 3. **Pass only FFI-safe types.** The `improper_ctypes` lint (warn by default) flags a declaration that takes a `String`, a `Vec` or a struct without a C-compatible representation. 4. **Pick the ABI on purpose.** `"C"` covers most libraries. `"system"` is for the Windows API. `"C-unwind"` is for functions that may unwind across the boundary. ## The habit interviewers listen for - Declare once, in one small module, and keep the raw items private. - Wrap each unsafe item in a safe Rust function that sets up its preconditions, for example by taking `&CStr` instead of a raw pointer. - Write a `SAFETY` comment at every unsafe call that names the contract it satisfies.

  • What happens if the declared Rust signature does not match the C function's real one?
    Nothing at build time: rustc sees only your declaration, and the linker matches the symbol by name, not by type. A wrong parameter type, a missing argument or a wrong return type compiles and links, and every call is undefined behaviour. That obligation is exactly what the `unsafe` on the block records, which is why generated bindings or a test against the real header pay off.
  • When is it right to declare an item in an `unsafe extern` block as `safe fn`?
    When no argument a safe caller can produce makes the C function misbehave, such as `abs(c_int)` or `sqrt(f64)`. A function taking a raw pointer, a pointer and a length, or one that depends on global C state usually does not qualify. Keep those unsafe and wrap them in a safe Rust function that establishes the precondition.
  • Which ABI does `unsafe extern { }` use when no ABI string is written?
    `"C"`. The Reference says the ABI defaults to C when the string is omitted, but also that the bare form is being phased out, so write `extern "C"` explicitly. Use `"system"` for Windows API functions and the `-unwind` variants only when unwinding must cross the boundary.

  • rustc checks the extern declaration against the C header.
  • Functions in an extern block are safe to call unless marked unsafe.
  • The unsafe before extern makes every call inside the block safe.
  • Edition 2024 still accepts a plain extern "C" block with only a warning.
  • Using i8 for C's char is portable to every target.

Assumes Rust 1.99 on edition 2024; unsafe extern blocks and safe items arrived in Rust 1.82, and the 2024 edition (Rust 1.85) made the unsafe keyword on extern blocks mandatory.

open as a page

In Rust, what can code inside an `unsafe` block do that safe code cannot, and which compiler checks keep running inside it?

level: juniorimportance: must knowfreq 78%

basics

~20 s

An unsafe block unlocks a few operations: dereferencing raw pointers, calling unsafe functions, using a static mut and reading union fields, while unsafe impl covers unsafe traits. Borrow checking, type checking and bounds checks all stay on.

open as a page

In Rust, what does it mean for a safe function that wraps `unsafe` code to be sound, and how is that different from correct?

level: middleimportance: must knowfreq 55%

basics

~20 s

A safe function is sound when no input or call sequence available to safe code can make it cause undefined behaviour. Correctness means returning the right result; a sound function may still be buggy, but its bugs stay defined.

open as a page

In Rust, why is `Option<&u64>` the same size as `&u64` while `Option<u32>` is twice the size of `u32`, and which sizes are guaranteed?

level: middleimportance: must knowfreq 55%

basics

~20 s

A reference is never null, so rustc encodes None as the null pointer and Option<&u64> stays 8 bytes. Every u32 bit pattern is valid, so Option<u32> needs a separate tag. Only a documented list of types gets this guarantee.

open as a page

In Rust, why does `let p = &raw mut x;` compile in safe code while `*p += 1;` fails with E0133?

level: middleimportance: must knowfreq 62%

basics

~20 s

Creating a raw pointer is harmless: it is only an address and may be null, dangling or aliased. Dereferencing it can touch invalid memory, so only the dereference, and pointer methods such as add or read, need an unsafe block.

open as a page

A Rust wrapper for a C compression library gets C-allocated buffers back and hands Rust-allocated strings to C; who frees each, and with what?

level: seniorimportance: must knowfreq 50%

basics

~20 s

Whoever allocated frees, with the matching function. Wrap C buffers in a Rust type whose Drop calls the library's free. Strings handed out with CString::into_raw come back to an exported Rust function that calls CString::from_raw.

open as a page

In Rust, why is a struct with fields `flag: u8, id: u32, kind: u8` 8 bytes by default but 12 bytes with `#[repr(C)]`?

level: juniorimportance: should knowfreq 45%

basics

~20 s

The default repr(Rust) lets rustc reorder fields, so it can put the u32 first and both u8 fields after it, padding only to 8. repr(C) keeps declaration order, so padding follows each u8 and the size grows to 12.

open as a page

In Rust, what does undefined behaviour mean for code inside an unsafe block, and why does a passing test not prove that block is correct?

level: juniorimportance: should knowfreq 45%

basics

~20 s

Undefined behaviour is any operation on the Reference's list, such as a data race or an invalid value. rustc optimises as if it never happens, so a program containing it has no defined meaning, and a passing test proves nothing.

open as a page

In Rust, why does making the `len` field of a `MaybeUninit`-backed stack vector `pub` break soundness when no `unsafe` code changed?

level: middleimportance: should knowfreq 40%

basics

~20 s

The unsafe code in as_slice and Drop trusts that buf[..len] is initialised. A pub len lets safe code in any module set it to any value, so safe code can cause undefined behaviour. Privacy is what keeps a safety invariant trustworthy.

open as a page

In Rust, why is `let p = CString::new(name).unwrap().as_ptr();` followed by a C call a bug, and when does `CString::new` fail?

level: middleimportance: should knowfreq 50%

basics

~20 s

The CString is a temporary dropped at the end of the let statement, so p dangles before C reads it. Bind the CString to a variable that outlives the call. CString::new returns Err(NulError) when the bytes contain an interior NUL.

open as a page

In Rust 2024, what does a function need so a C program can call it by name, and what do `extern "C"` and `#[unsafe(no_mangle)]` each do?

level: middleimportance: should knowfreq 45%

basics

~10 s

extern "C" gives the function C's calling convention; #[unsafe(no_mangle)] keeps its symbol name unmangled so the C linker finds it. Any struct it passes needs #[repr(C)], and edition 2024 requires the unsafe(...) wrapper.

open as a page

In Rust, why does `size_of::<str>()` fail to compile while `size_of::<&str>()` is 16 and `size_of::<()>()` is 0 on a 64-bit target?

level: middleimportance: should knowfreq 35%

basics

~20 s

str is dynamically sized, and size_of::<T>() requires T: Sized, so rustc reports E0277. A &str is a wide pointer, data address plus length, 16 bytes today. () is a zero-sized type, guaranteed size 0, alignment 1.

open as a page

In Rust 2024, why does an `unsafe fn` that dereferences a raw pointer without an inner `unsafe` block compile only with a warning?

level: middleimportance: should knowfreq 48%

basics

~20 s

Since the 2024 edition the body of an unsafe fn is no longer an unsafe context: the unsafe_op_in_unsafe_fn lint warns on each unsafe operation there. The fix is an explicit unsafe block with a SAFETY comment citing the caller's contract.

open as a page

What does running `cargo miri test` catch in a Rust crate's unsafe code, and what can Miri not tell you?

level: middleimportance: should knowfreq 40%

basics

~20 s

Miri interprets the crate's tests and stops at undefined behaviour it observes: invalid or uninitialised values, out-of-bounds or misaligned accesses, aliasing violations, data races, leaks. It sees only executed paths and cannot run most foreign calls.

open as a page

A Rust parser transmutes wire bytes into a `#[repr(C)]` header with a `bool` field; why is a byte of 2 undefined behaviour?

level: middleimportance: should knowfreq 42%

basics

~20 s

A bool may only hold 0 or 1, and producing any other value is immediate undefined behaviour. mem::transmute checks only that the sizes match, so the parser must validate the byte and build the header field by field.

open as a page

How does Rust's standard library implement the safe `<[T]>::split_at_mut`, and which checks keep its `unsafe` body sound?

level: seniorimportance: should knowfreq 45%

basics

~20 s

It checks mid <= len, panicking with "mid > len" otherwise, takes one raw pointer from as_mut_ptr, and builds from_raw_parts_mut(ptr, mid) and from_raw_parts_mut(ptr.add(mid), len - mid). The ranges cannot overlap and both borrow from the input.

open as a page

In Rust, a type owning a heap value through `NonNull<T>` needs `unsafe impl Send` — which bounds on `T` make that impl sound, and why?

level: seniorimportance: should knowfreq 38%

basics

~20 s

NonNull<T> makes the type neither Send nor Sync. For a uniquely owning type, write unsafe impl<T: Send> Send and unsafe impl<T: Sync> Sync; leaving out T: Send lets an Rc cross threads, and that is unsound.

open as a page

A Rust progress callback passed to a C library as an `extern "C"` function panics; what happens in Rust 1.99, and how should the wrapper prevent it?

level: seniorimportance: should knowfreq 40%

basics

~20 s

Since Rust 1.81 the panic aborts the whole process at the extern "C" boundary instead of unwinding into C. The wrapper's callback should run user code inside catch_unwind and return an error code to C.

open as a page

A Rust `#[repr(C, packed)]` packet header fails with E0793 at `&h.seq` and at `println!("{}", h.len)`: why, and how do you read those fields?

level: seniorimportance: should knowfreq 25%

basics

~20 s

repr(packed) lowers the struct's alignment to 1, so a u32 or u16 field may be misaligned, and even creating a misaligned reference is undefined behaviour. Copy the field out ({ h.len }) or take &raw const and call read_unaligned.

open as a page

In Rust, why mark a newtype like `struct Pid(c_int)` `#[repr(transparent)]` rather than `#[repr(C)]` before passing it to C as an int, and what fields may it hold?

level: seniorimportance: should knowfreq 30%

basics

~20 s

repr(transparent) gives the newtype the same layout and ABI as its single non-trivial field, so C sees a plain int. repr(C) only promises a C struct's layout and ABI. Other fields must be size 0, alignment 1, like PhantomData.

open as a page

In Rust 2024, why does `println!("{}", COUNTER)` on a `static mut COUNTER: u32` fail to compile while `COUNTER += 1` in the same unsafe block compiles?

level: seniorimportance: should knowfreq 42%

basics

~20 s

println! borrows its arguments, so it creates a shared reference to the static mut, which the static_mut_refs lint denies by default on edition 2024. COUNTER += 1 writes the place directly and creates no reference.

open as a page

In Rust, what does declaring an `unsafe trait` promise, and why may unsafe code trust an `unsafe impl` but not a safe trait's impl?

level: seniorimportance: should knowfreq 35%

basics

~20 s

An unsafe trait says every implementation upholds a condition the compiler cannot check, signed with unsafe impl. Unsafe code may rely on that promise; a safe trait's impl may be wrong, so relying on it must never risk undefined behaviour.

open as a page

In Rust, why is `mem::zeroed::<&u32>()` undefined behaviour, and how does `MaybeUninit<T>` let unsafe code defer initialisation soundly?

level: seniorimportance: should knowfreq 35%

basics

~20 s

A reference must be non-null, so an all-zero &u32 is an invalid value the moment it exists. MaybeUninit<T> holds bytes that need not be valid; you write the value and call assume_init only once it is fully initialised.

open as a page

A Rust optimisation creates two `&mut [u8; 8]` to one buffer from a raw pointer and the output is correct; why is it still undefined behaviour?

level: seniorimportance: should knowfreq 40%

basics

~20 s

A live &mut T must be the only reference to its memory. Using the first &mut after the second one was created and written breaks the aliasing rules, which is UB however the output looks; Miri reports it.

open as a page

As the lead of a Rust codebase, what policy would you set for `unsafe` code, and how would you enforce it with rustc lints, Clippy and Miri?

level: principalimportance: should knowfreq 25%

basics

~20 s

Ban unsafe by default with the unsafe_code lint, allow it only in small named modules with private invariants, require // SAFETY: comments through Clippy's undocumented_unsafe_blocks, run Miri over those modules' tests in CI, and require an experienced second reviewer.

open as a page

Leading a Rust team that wraps a C compression library, would you generate the bindings with bindgen or write them by hand, and where does the safe boundary go?

level: principalimportance: should knowfreq 30%

basics

~20 s

Generate with bindgen when the header is large or changes, write by hand for a few stable functions. Either way, raw declarations sit in a thin sys layer, and a separate safe layer holds the unsafe calls, ownership and error mapping.

open as a page

In Rust, why is a stack vector's `extend_from_slice` unsound if it raises `len` before cloning each item into `MaybeUninit` slots, and how do you fix it?

level: seniorimportance: nice to knowfreq 28%

basics

~20 s

T::clone may panic. If len already counts unwritten slots, unwinding drops the vector and Drop calls assume_init_drop on uninitialised memory. Raise len only after each write, or use a guard, so every state a panic can leave is safe.

open as a page