Blog

Part 28 · Unsafe Rust: Raw Pointers and Safe APIs Over Unsafe Code

The unsafe keyword unlocks five extra abilities, such as reading through a raw pointer. It doesn’t switch off the borrow checker. This part shows what unsafe allows, what undefined behaviour is, and how to wrap unsafe code in a safe API.

Everything in this series so far has been safe Rust. The compiler checked every borrow, and no program could read freed memory. Some jobs need more freedom than that: the inside of Vec, a call into a C library, a slice split in two. For those, Rust has the unsafe keyword.

This part covers what unsafe allows and what it doesn’t, raw pointers, undefined behaviour, unsafe fn and its # Safety notes, and the main skill: building a safe API around a small unsafe core. We’ll write our own split_at_mut and a fixed-size stack, then look at static mut, unsafe impl Send and calling C. It builds on borrowing from Part 7, Drop from Part 22 and Send from Part 23. Every program here was run on Rust 1.95, and its output is pasted from the run.

Try this first

This program makes a pointer to x, then reads through it. Decide which of the two lines the compiler objects to, if either:

fn main() {
    let x = 42;
    let p = &raw const x;
    println!("made a pointer");
    println!("{}", *p);
}

It prints:

error[E0133]: dereference of raw pointer is unsafe and requires unsafe block
 --> src/main.rs:5:20
  |
5 |     println!("{}", *p);
  |                    ^^ dereference of raw pointer
  |
  = note: raw pointers may be null, dangling or unaligned; they can violate aliasing rules and cause data races: all of these are undefined behavior

Making the pointer is fine. Line 3 compiles. Reading through it on line 5 is the problem. p isn’t a reference like &x. It’s a raw pointer, a plain memory address with no borrow attached. The compiler can’t prove that address is still good, so it won’t let you read it in safe code.

The note lists what can go wrong: the pointer might be null, dangling or unaligned. Keep that list in mind. Most of this part is about making sure none of those things happen.

What unsafe allows

The unsafe keyword unlocks five things that safe Rust doesn’t allow. The Rust book calls them the unsafe superpowers. Four of them happen inside an unsafe block; the third is written unsafe impl:

  1. Dereference a raw pointer (read or write through it).
  2. Call an unsafe function, including functions from C.
  3. Implement an unsafe trait, such as Send or Sync.
  4. Read or write a mutable static, a static mut.
  5. Read a field of a union. A union is a type whose fields all share the same bytes. It’s mostly used to talk to C, and we won’t need it here.

Those are the ones you’ll use. (A few rarer cases also need the keyword, such as the unsafe extern blocks at the end of this part.) unsafe doesn’t turn off the borrow checker, the type checker or anything else. Here are two &mut borrows of the same variable, inside an unsafe block:

fn main() {
    let mut n = 1;
    unsafe {
        let a = &mut n;
        let b = &mut n;
        *a += 1;
        *b += 1;
    }
    println!("{n}");
}

It prints:

warning: unnecessary `unsafe` block
...
error[E0499]: cannot borrow `n` as mutable more than once at a time
 --> src/main.rs:5:17
  |
4 |         let a = &mut n;
  |                 ------ first mutable borrow occurs here
5 |         let b = &mut n;
  |                 ^^^^^^ second mutable borrow occurs here
6 |         *a += 1;
  |         ------- first borrow later used here

Same error as Part 7, and the compiler even warns that the unsafe did nothing. References are still checked. Only the five abilities above are unlocked.

Raw pointers

Rust has two raw pointer types. *const T is a pointer you read through. *mut T is a pointer you may also write through. You make them from a place with &raw const and &raw mut, which have been stable since Rust 1.82. You’ll also see the older way, a cast with as:

fn main() {
    let mut count = 5;
    let p: *mut i32 = &raw mut count;
    println!("p is null? {}", p.is_null());

    // SAFETY: `p` points at `count`, which is alive until the end of
    // main, and nothing else reads or writes `count` inside this block.
    unsafe {
        *p += 1;
        println!("through p: {}", *p);
    }
    println!("count is {count}");

    let limit = 10;
    let q = &limit as *const i32;
    // SAFETY: `q` points at `limit`, which is alive and never changes.
    let seen = unsafe { *q };
    println!("through q: {seen}");

    let nowhere: *const i32 = std::ptr::null();
    println!("nowhere is null? {}", nowhere.is_null());
}

It prints:

p is null? false
through p: 6
count is 6
through q: 10
nowhere is null? true

A raw pointer is like a reference with the rules taken off:

  • It has no lifetime, so the compiler doesn’t stop it outliving its value.
  • It can be null. std::ptr::null() makes one on purpose.
  • You can have a *mut and a *const to the same place at once.
  • Dropping it frees nothing. It doesn’t own what it points at.

Making, copying, comparing and printing raw pointers is all safe. Nothing can go wrong until you follow one, so only following one needs unsafe.

Every unsafe block in this part has a // SAFETY: comment above it. The comment says why the block is sound: which rule it might break, and why it doesn’t. The compiler doesn’t read it. The next person to change the code does. Clippy has a lint for this, undocumented_unsafe_blocks. It’s off by default; projects with a lot of unsafe code switch it on.

Undefined behaviour

When you write unsafe, you promise the compiler that your code follows Rust’s rules. If you break that promise, the result is undefined behaviour, usually shortened to UB. Rust doesn’t say what happens next. The program might crash, print the right answer, print the wrong one, or work today and fail after the next compiler upgrade. The optimiser assumes UB never happens, so it can turn one wrong line into strange results somewhere else entirely.

Here’s the most common kind, a dangling pointer. It compiles, and clippy passes it. Don’t run it.

fn main() {
    let p: *const i32;
    {
        let x = 5;
        p = &raw const x;
    }
    // SAFETY: none. `x` is gone, so `p` dangles. This is the bug.
    let v = unsafe { *p };
    println!("{v}");
}

x died at the }, and p still holds its old address. With a reference instead of a raw pointer, this would be a compile error (Part 9). With a raw pointer, the compiler takes your word for it.

Other kinds of UB that unsafe code can cause:

  • Two live &mut to the same value. Safe code can’t make this. Raw pointers can, by turning one address into two &mut references.
  • Reading out of bounds. slice.get_unchecked(10) on a 3-item slice reads whatever memory comes next.
  • Reading memory that was never set, or a value that isn’t valid for its type, such as a bool holding the byte 7.
  • A data race: two threads touch the same memory at once, and at least one writes.

There’s a tool that catches many of these while the program runs. It’s called Miri, and it runs your program in an interpreter that checks every memory access. It needs the nightly toolchain (rustup +nightly component add miri, then cargo +nightly miri run). Miri isn’t installed on the machine this series was checked on, so we haven’t run it here. If you write real unsafe code, run your tests under it.

unsafe fn and the # Safety section

Some functions are only correct when the caller promises something the compiler can’t check. They’re marked unsafe fn, and calling one needs an unsafe block. Their docs have a # Safety section that spells out the promise.

Since edition 2024, the body of an unsafe fn is checked like normal code. An unsafe operation inside it still needs its own unsafe block. By default that’s a warning, from the lint unsafe_op_in_unsafe_fn. We turn it into an error here, so you can see what it says:

#![deny(unsafe_op_in_unsafe_fn)]

/// Returns the item `i` places after `start`.
///
/// # Safety
///
/// `start` must point into an array of `i32` that has at least `i + 1`
/// items from `start` onwards, and the array must be alive.
unsafe fn read_at(start: *const i32, i: usize) -> i32 {
    *start.add(i)
}

fn main() {
    let a = [1, 2, 3];
    // SAFETY: `a` has 3 items, so index 2 is in range.
    println!("{}", unsafe { read_at(a.as_ptr(), 2) });
}

It prints:

error[E0133]: dereference of raw pointer is unsafe and requires unsafe block
...
note: an unsafe function restricts its caller, but its body is safe by default
...
error[E0133]: call to unsafe function `std::ptr::const_ptr::<impl *const T>::add` is unsafe and requires unsafe block

The note says it well: unsafe fn puts a duty on the caller. It doesn’t give the body any extra freedom. ptr.add(i) is itself an unsafe function, because moving a pointer past the end of its allocation is UB. Wrap the body in its own block, with its own reason:

/// Returns the item `i` places after `start`.
///
/// # Safety
///
/// `start` must point into an array of `i32` that has at least `i + 1`
/// items from `start` onwards, and the array must be alive.
unsafe fn read_at(start: *const i32, i: usize) -> i32 {
    // SAFETY: the caller promised that `start + i` is inside a live array.
    unsafe { *start.add(i) }
}

fn main() {
    let a = [1, 2, 3];
    // SAFETY: `a` has 3 items, so index 2 is in range.
    let v = unsafe { read_at(a.as_ptr(), 2) };
    println!("item 2 is {v}");
}

It prints:

item 2 is 3

Now the promise is written down twice: once in # Safety, where callers read it, and once at each call site, where the caller says why they kept it.

Safe outside, unsafe inside

You rarely want callers to write unsafe at all. The usual design is the other way round: a small unsafe core, hidden behind functions anyone can call safely. Vec, String, Rc and Mutex are all built this way. Their insides use raw pointers. Their public methods don’t need unsafe.

For that to work, the safe functions must make sure the core’s rules hold for every possible input. If any input, however odd, can cause UB, the function shouldn’t be safe. The fields that the rules depend on, such as a pointer and a length, stay private, so code outside the module can’t break them.

safe code: the borrow checker and type checker apply everywhere callers main() your code another crate one module: fields are private split_at_mut MyStack::push / pop safe public API unsafe core from_raw_parts_mut assume_init_read assume_init_drop what the core relies on: ptr is valid for len items the two halves don't overlap slots 0..len are initialised private: no way in

Callers reach the unsafe core only through the safe API. The API checks its inputs, and private fields stop anyone else from breaking the rules listed next to the core.

Reading the picture from left to right:

  1. Callers live in safe code. They can only call public functions.
  2. The public functions, split_at_mut and MyStack::push and pop, sit on the module’s edge. They check what they’re given, such as “is mid inside the slice?” or “is the stack full?”.
  3. Only then do they enter the small unsafe core.
  4. The core relies on a few rules, listed next to it. The API’s checks and the private fields together make sure those rules always hold.
  5. A caller that tries to reach the pointer or length directly gets a compile error, because the fields are private.

Explain it like I’m ten

Think of a school science lab. Most of the room is open: anyone can sit at a desk, read, draw and build with blocks. In one corner is a locked cupboard with the strong chemicals. Students can’t open it. When a class needs something from it, they ask the teacher. The teacher checks the request, measures the right amount, and hands over a safe, labelled cup.

The cupboard is the unsafe core. The teacher is the safe API. The students are the callers. Nobody had to ban chemicals from the school. They just made sure the only way to them goes through someone who checks.

The precise version

unsafe marks code whose soundness the compiler can’t check, so a person must. An unsafe block says “I checked this”. An unsafe fn says “the caller must check this, and here’s what”. A safe function that contains an unsafe block says “no input from safe code can cause UB”. That last promise covers every caller and every input, forever. That’s why the unsafe parts are kept small, the fields they depend on are private, and every block gets a // SAFETY: comment that a reviewer can check.

Where the analogy breaks: a teacher who hands out the wrong chemical can be seen and stopped. A wrong unsafe block often isn’t noticed at all. The program can run fine for years, then fail far from the bug, after an unrelated change or a new compiler version. Also, the cupboard isn’t locked against the teacher: inside the module, every line can break the rules, not just the lines inside unsafe.

Worked example: split_at_mut by hand

The standard library has slice::split_at_mut. It takes one &mut [T] and gives back two &mut slices, one for each side of an index. Let’s write our own for i32, in safe Rust first:

fn split_at_mut(values: &mut [i32], mid: usize) -> (&mut [i32], &mut [i32]) {
    (&mut values[..mid], &mut values[mid..])
}

fn main() {
    let mut v = [1, 2, 3, 4];
    let (a, b) = split_at_mut(&mut v, 2);
    a[0] = 10;
    b[0] = 30;
    println!("{v:?}");
}

It prints:

error[E0499]: cannot borrow `*values` as mutable more than once at a time
 --> src/main.rs:2:31
  |
1 | fn split_at_mut(values: &mut [i32], mid: usize) -> (&mut [i32], &mut [i32]) {
  |                         - let's call the lifetime of this reference `'1`
2 |     (&mut values[..mid], &mut values[mid..])
  |     --------------------------^^^^^^--------
  |     |     |                   |
  |     |     |                   second mutable borrow occurs here
  |     |     first mutable borrow occurs here
  |     returning this value requires that `*values` is borrowed for `'1`

Read it bottom up. Both results must live as long as '1, the caller’s borrow. The first &mut values[..mid] borrows all of values, and the second tries to borrow all of it again. The borrow checker tracks values as one thing. It doesn’t know that ..mid and mid.. never overlap.

We know they don’t. So we do the one step the checker can’t, with raw pointers, and keep it small:

use std::slice;

fn split_at_mut(values: &mut [i32], mid: usize) -> (&mut [i32], &mut [i32]) {
    let len = values.len();
    assert!(mid <= len, "mid {mid} is past the end ({len})");
    let ptr = values.as_mut_ptr();
    // SAFETY: `ptr` comes from a live `&mut [i32]` of `len` items, so it is
    // valid for `len` items. The assert keeps `mid <= len`, so the first
    // half (0..mid) and the second half (mid..len) stay inside it and don't
    // overlap. Both results borrow from `values`, so it can't be used
    // while they are alive.
    unsafe {
        (
            slice::from_raw_parts_mut(ptr, mid),
            slice::from_raw_parts_mut(ptr.add(mid), len - mid),
        )
    }
}

fn main() {
    let mut scores = [10, 20, 30, 40, 50];
    let (left, right) = split_at_mut(&mut scores, 2);
    left[0] += 1;
    right[0] += 1;
    println!("left {left:?}, right {right:?}");
    println!("scores {scores:?}");

    let (all, none) = split_at_mut(&mut scores, 5);
    println!("{} and {}", all.len(), none.len());
}

It prints:

left [11, 20], right [31, 40, 50]
scores [11, 20, 31, 40, 50]
5 and 0

as_mut_ptr gives the address of the first item. slice::from_raw_parts_mut(ptr, n) is an unsafe function that builds a &mut [i32] of n items starting at ptr. ptr.add(mid) moves the pointer mid items forward.

The assert! is what makes the function safe. Without it, split_at_mut(&mut scores, 6) would build a slice that runs past the end of the array, and that’s UB. With it, the call panics with mid 6 is past the end (5) instead. A panic is safe: it’s a clean, defined stop. That’s the job of the safe layer: turn every bad input into a panic or an error, never into UB.

Notice also what the signature does. The two results have the same lifetime as values. So after the unsafe block, the borrow checker is back on duty: scores can’t be used while left and right are alive, exactly as with the real split_at_mut.

Worked example: a stack with a fixed size

Next, a container. MyStack<T, N> holds up to N items in an array, with no heap allocation. The trouble is that a fresh stack has no items, but an array [T; N] needs N real values. std::mem::MaybeUninit<T> solves that. It’s a slot with room for one T that may or may not hold one yet. The compiler doesn’t track which, so we do it ourselves with len. Our rule: slots 0..len hold a value; the rest don’t.

To prove nothing leaks and nothing drops twice, the items are a Tracked type that counts its own drops in an atomic counter from Part 24:

use std::mem::MaybeUninit;
use std::sync::atomic::{AtomicUsize, Ordering};

struct MyStack<T, const N: usize> {
    items: [MaybeUninit<T>; N],
    len: usize,
}

impl<T, const N: usize> MyStack<T, N> {
    fn new() -> Self {
        MyStack {
            items: [const { MaybeUninit::uninit() }; N],
            len: 0,
        }
    }

    fn push(&mut self, value: T) -> Result<(), T> {
        if self.len == N {
            return Err(value);
        }
        self.items[self.len].write(value);
        self.len += 1;
        Ok(())
    }

    fn pop(&mut self) -> Option<T> {
        if self.len == 0 {
            return None;
        }
        self.len -= 1;
        // SAFETY: slots 0..len are always initialised. The old len was
        // one more than the new one, so this slot was initialised, and
        // we just lowered len, so nothing will read or drop it again.
        Some(unsafe { self.items[self.len].assume_init_read() })
    }
}

impl<T, const N: usize> Drop for MyStack<T, N> {
    fn drop(&mut self) {
        for slot in &mut self.items[..self.len] {
            // SAFETY: slots 0..len are initialised, and the stack is
            // going away, so each one is dropped exactly once.
            unsafe { slot.assume_init_drop() };
        }
    }
}

static DROPS: AtomicUsize = AtomicUsize::new(0);

struct Tracked(u32);

impl Drop for Tracked {
    fn drop(&mut self) {
        DROPS.fetch_add(1, Ordering::Relaxed);
        println!("drop {}", self.0);
    }
}

fn main() {
    {
        let mut stack: MyStack<Tracked, 3> = MyStack::new();
        for n in 1..=4 {
            match stack.push(Tracked(n)) {
                Ok(()) => println!("pushed {n}"),
                Err(t) => println!("full, got {} back", t.0),
            }
        }
        let top = stack.pop();
        println!("popped {}", top.as_ref().map_or(0, |t| t.0));
        println!("leaving the block with 2 items still inside");
    }
    println!("drops: {} (made 4)", DROPS.load(Ordering::Relaxed));
}

It prints:

pushed 1
pushed 2
pushed 3
full, got 4 back
drop 4
popped 3
leaving the block with 2 items still inside
drop 3
drop 1
drop 2
drops: 4 (made 4)

Four values made, four drops, each number once. Let’s follow them:

  • push checks len == N first. A full stack hands the value back in Err, so Tracked(4) returns to the caller, and it’s dropped at the end of that match arm. write is safe: it puts a value into a slot and never reads the old contents.
  • pop lowers len and then moves the value out with assume_init_read. That function is unsafe because it copies the bits out and trusts that they form a real T. After it, the slot is outside 0..len, so nobody treats it as full again.
  • At the closing }, top goes first (it was declared last, as in Part 6), which prints drop 3. Then the stack’s own Drop runs and drops the two items still in slots 0 and 1.

The Drop impl isn’t optional. MaybeUninit never drops what it holds, because it doesn’t know whether it holds anything. Leave out Drop, and the two items left in the stack are never dropped. Exercise 1 checks that.

Both methods take &mut self, and the fields are private to the module that defines them (here, the whole file). So the rule “slots 0..len hold a value” can only change inside these few lines, which is what makes it possible to check by reading.

static mut, and why edition 2024 pushes back

A static is one value for the whole program. A static mut can change, and every use of it needs unsafe, because any thread could touch it at the same time. Here’s a visit counter:

static mut VISITS: u32 = 0;

fn visit() {
    // SAFETY: only main's thread calls visit.
    unsafe { VISITS += 1 };
}

fn main() {
    visit();
    visit();
    // SAFETY: as above; nothing else touches VISITS.
    unsafe { println!("visits: {}", VISITS) };
}

It prints:

error: creating a shared reference to mutable static
  --> src/main.rs:12:37
   |
12 |     unsafe { println!("visits: {}", VISITS) };
   |                                     ^^^^^^ shared reference to mutable static
   |
   = note: shared references to mutable statics are dangerous; it's undefined behavior if the static is mutated or if a mutable reference is created for it while the shared reference lives
...
   = note: `#[deny(static_mut_refs)]` (part of `#[deny(rust_2024_compatibility)]`) on by default

VISITS += 1 compiled. The println! didn’t, because println! takes a reference to its arguments, and edition 2024 denies any & or &mut to a static mut. A reference promises “nobody changes this while I hold it”, and with a global that anyone can write to, that promise is almost impossible to keep. This lint has no error code, just the name static_mut_refs.

The fix is to not use static mut. An atomic from Part 24 can sit in a plain static, needs no unsafe, and is correct across threads too:

use std::sync::atomic::{AtomicU32, Ordering};

static VISITS: AtomicU32 = AtomicU32::new(0);

fn visit() -> u32 {
    VISITS.fetch_add(1, Ordering::Relaxed) + 1
}

fn main() {
    visit();
    visit();
    println!("visit number {}", visit());
}

It prints:

visit number 3

For anything bigger than a number, put a Mutex in the static instead.

unsafe impl Send

Part 23 said you never write impl Send yourself, because the compiler works it out from the fields. A raw pointer field changes that. Raw pointers are neither Send nor Sync, so a struct holding one can’t move to another thread. Sometimes that’s too careful. Here’s a type that owns one u64 on the heap through a raw pointer, the way Box does inside:

mod raw_box {
    pub struct RawBox {
        ptr: *mut u64,
    }

    impl RawBox {
        pub fn new(value: u64) -> RawBox {
            RawBox {
                ptr: Box::into_raw(Box::new(value)),
            }
        }

        pub fn add(&mut self, n: u64) {
            // SAFETY: `ptr` came from `Box::into_raw` in `new` and is freed
            // only in `drop`, so it is valid. `&mut self` means nobody else
            // is using this RawBox right now.
            unsafe { *self.ptr += n }
        }

        pub fn get(&self) -> u64 {
            // SAFETY: as in `add`; `&self` means nobody is writing.
            unsafe { *self.ptr }
        }
    }

    impl Drop for RawBox {
        fn drop(&mut self) {
            // SAFETY: `ptr` came from `Box::into_raw`, and drop runs once,
            // so we turn it back into a Box and free it exactly once.
            drop(unsafe { Box::from_raw(self.ptr) });
        }
    }

    // SAFETY: a RawBox is the only owner of its u64, just like a Box<u64>.
    // No other pointer to that u64 exists, so moving the RawBox to another
    // thread moves all access to the u64 with it.
    unsafe impl Send for RawBox {}
}

use raw_box::RawBox;
use std::thread;

fn main() {
    let mut total = RawBox::new(40);
    total.add(1);
    let handle = thread::spawn(move || {
        total.add(1);
        total.get()
    });
    println!("the thread saw {}", handle.join().unwrap());
}

It prints:

the thread saw 42

Box::into_raw gives up the Box and hands back its pointer. Box::from_raw turns it back into a Box, which frees the memory when dropped. Without the unsafe impl Send line, thread::spawn fails with E0277: “*mut u64 cannot be sent between threads safely”, the same error shape as Rc in Part 23.

Send is an unsafe trait. Implementing it has no methods to write. It’s purely a promise, and a wrong promise means a data race. That’s why it needs unsafe impl. We didn’t implement Sync, because we didn’t need to share a &RawBox between threads.

The mod raw_box matters too. Outside it, ptr is private. Code in main can’t write total.ptr = std::ptr::null_mut() (that’s E0616, “field ptr of struct RawBox is private”), so it can’t break the rule our SAFETY comments rely on.

Calling C

The other big use of unsafe is calling code written in another language. You declare the C functions in an extern "C" block. Since edition 2024 the block itself must be written unsafe extern "C"; plain extern "C" fails with “extern blocks must be unsafe”. The reason is that Rust can’t check your declaration against the real C function. If you get a type wrong, that’s UB. The C standard library is linked into every Rust program on Linux, so we can call its abs with no setup:

use std::ffi::c_int;

unsafe extern "C" {
    fn abs(input: c_int) -> c_int;
}

fn main() {
    // SAFETY: `abs` is declared with C's own types, and -7 is not
    // INT_MIN, so C's abs won't overflow.
    let a = unsafe { abs(-7) };
    println!("abs(-7) = {a}");
}

It prints:

abs(-7) = 7

c_int is Rust’s name for C’s int, so the declaration matches on every platform. Calling the function needs unsafe, because Rust can’t see what C code does. If you’ve checked that a C function is fine for every input, Rust (since 1.82) also lets you mark it safe fn inside the block, and then calling it needs no unsafe. Real projects wrap C libraries the same way as MyStack: a thin unsafe layer and a safe Rust API on top. The bindgen tool can write the extern declarations for you from a C header.

Tips and traps

  • Making the unsafe block bigger than needed. Wrapping a whole function in unsafe hides which line needs it, and a reviewer must check all of it. Wrap only the operation that needs it, with a // SAFETY: comment saying why it’s sound.
  • A safe function that can cause UB. If some input to your safe function leads to UB, the bug is in your function, not in the caller. Check inputs with assert! or return an error, as split_at_mut did. If you can’t check the rule, make the function unsafe fn and write a # Safety section.
  • Forgetting Drop around MaybeUninit or raw pointers. Nothing frees them for you. The program compiles and runs, and memory quietly leaks. Count drops in a test, as we did with Tracked.
  • Thinking “it ran fine, so it’s correct”. UB can give the right answer for years. Run tests under Miri, and argue each SAFETY comment instead of trusting output.
  • Reaching for static mut. Edition 2024 denies taking & of it, and println! does that behind your back. Use an atomic, a Mutex, or std::sync::OnceLock in a plain static.
  • unsafe doesn’t silence the borrow checker. If you get E0499 or E0502, unsafe won’t help. The fix is still restructuring the code, or a safe API like split_at_mut that someone already proved.

unsafe doesn’t switch off Rust’s checks; it marks the few lines where you do the checking, so keep them small and wrap them in a safe API.

Exercises

Exercise 1. Delete the whole impl Drop for MyStack block from the stack example and run it again. Predict the last line it prints, and which drop lines disappear.

Exercise 2. Add a method fn peek(&self) -> Option<&T> to MyStack that returns the top item without removing it. You’ll need MaybeUninit::assume_init_ref. Write its // SAFETY: comment.

Exercise 3. Using our split_at_mut from above (no new unsafe), write fn first_and_last(values: &mut [i32]) -> Option<(&mut i32, &mut i32)>. It returns None when the slice has fewer than 2 items. Use it to swap the first and last items of [1, 2, 3, 4].

Answers

1. The last line is drops: 2 (made 4). drop 1 and drop 2 disappear. Tracked(4) was handed back by push and Tracked(3) was moved out by pop, so both are still dropped normally. The two left in the stack sit in MaybeUninit slots, and MaybeUninit never drops its contents. They leak.

use std::mem::MaybeUninit;
use std::sync::atomic::{AtomicUsize, Ordering};

struct MyStack<T, const N: usize> {
    items: [MaybeUninit<T>; N],
    len: usize,
}

impl<T, const N: usize> MyStack<T, N> {
    fn new() -> Self {
        MyStack {
            items: [const { MaybeUninit::uninit() }; N],
            len: 0,
        }
    }

    fn push(&mut self, value: T) -> Result<(), T> {
        if self.len == N {
            return Err(value);
        }
        self.items[self.len].write(value);
        self.len += 1;
        Ok(())
    }

    fn pop(&mut self) -> Option<T> {
        if self.len == 0 {
            return None;
        }
        self.len -= 1;
        // SAFETY: slots 0..len are always initialised. The old len was
        // one more than the new one, so this slot was initialised, and
        // we just lowered len, so nothing will read or drop it again.
        Some(unsafe { self.items[self.len].assume_init_read() })
    }
}

static DROPS: AtomicUsize = AtomicUsize::new(0);

struct Tracked(u32);

impl Drop for Tracked {
    fn drop(&mut self) {
        DROPS.fetch_add(1, Ordering::Relaxed);
        println!("drop {}", self.0);
    }
}

fn main() {
    {
        let mut stack: MyStack<Tracked, 3> = MyStack::new();
        for n in 1..=4 {
            match stack.push(Tracked(n)) {
                Ok(()) => println!("pushed {n}"),
                Err(t) => println!("full, got {} back", t.0),
            }
        }
        let top = stack.pop();
        println!("popped {}", top.as_ref().map_or(0, |t| t.0));
        println!("leaving the block with 2 items still inside");
    }
    println!("drops: {} (made 4)", DROPS.load(Ordering::Relaxed));
}

It prints:

pushed 1
pushed 2
pushed 3
full, got 4 back
drop 4
popped 3
leaving the block with 2 items still inside
drop 3
drops: 2 (made 4)

A leak isn’t UB, so Rust allows it, and nothing warns you. That’s why the drop-counting test is worth writing.

2. The top item is in slot len - 1, when len isn’t 0. The returned &T borrows self, so nobody can pop or push while it’s alive.

use std::mem::MaybeUninit;

struct MyStack<T, const N: usize> {
    items: [MaybeUninit<T>; N],
    len: usize,
}

impl<T, const N: usize> MyStack<T, N> {
    fn new() -> Self {
        MyStack {
            items: [const { MaybeUninit::uninit() }; N],
            len: 0,
        }
    }

    fn push(&mut self, value: T) -> Result<(), T> {
        if self.len == N {
            return Err(value);
        }
        self.items[self.len].write(value);
        self.len += 1;
        Ok(())
    }

    fn peek(&self) -> Option<&T> {
        if self.len == 0 {
            return None;
        }
        // SAFETY: slots 0..len are initialised and len > 0, so slot
        // len - 1 holds a value. The &T borrows self, so the stack can't
        // pop or drop that value while the reference is alive.
        Some(unsafe { self.items[self.len - 1].assume_init_ref() })
    }
}

impl<T, const N: usize> Drop for MyStack<T, N> {
    fn drop(&mut self) {
        for slot in &mut self.items[..self.len] {
            // SAFETY: slots 0..len are initialised, and the stack is
            // going away, so each one is dropped exactly once.
            unsafe { slot.assume_init_drop() };
        }
    }
}

fn main() {
    let mut stack: MyStack<String, 2> = MyStack::new();
    println!("empty: {:?}", stack.peek());
    stack.push(String::from("first")).unwrap();
    stack.push(String::from("second")).unwrap();
    println!("top: {:?}", stack.peek());
    println!("still top: {:?}", stack.peek());
}

It prints:

empty: None
top: Some("second")
still top: Some("second")

3. Split after the first item. The first half’s item 0 is the first item, and the second half’s last item is the last one. The two halves don’t overlap, so the two &mut don’t either. All the unsafe work was already done, and checked, inside split_at_mut.

use std::slice;

fn split_at_mut(values: &mut [i32], mid: usize) -> (&mut [i32], &mut [i32]) {
    let len = values.len();
    assert!(mid <= len, "mid {mid} is past the end ({len})");
    let ptr = values.as_mut_ptr();
    // SAFETY: `ptr` comes from a live `&mut [i32]` of `len` items, so it is
    // valid for `len` items. The assert keeps `mid <= len`, so the first
    // half (0..mid) and the second half (mid..len) stay inside it and don't
    // overlap. Both results borrow from `values`, so it can't be used
    // while they are alive.
    unsafe {
        (
            slice::from_raw_parts_mut(ptr, mid),
            slice::from_raw_parts_mut(ptr.add(mid), len - mid),
        )
    }
}

fn first_and_last(values: &mut [i32]) -> Option<(&mut i32, &mut i32)> {
    if values.len() < 2 {
        return None;
    }
    let (head, tail) = split_at_mut(values, 1);
    Some((&mut head[0], tail.last_mut()?))
}

fn main() {
    let mut v = [1, 2, 3, 4];
    if let Some((a, b)) = first_and_last(&mut v) {
        std::mem::swap(a, b);
    }
    println!("{v:?}");

    let mut one = [9];
    println!("{:?}", first_and_last(&mut one));
}

It prints:

[4, 2, 3, 1]
None

What’s next

unsafe let us step past the compiler’s checks in a few small, well-marked places. In Part 29, we’ll go the other way and make the compiler write code for us, with declarative macros and macro_rules!.

How useful was this post?

Click on a heart to rate it!

Average rating 0 / 5. Vote count: 0

No votes so far! Be the first to rate this post.