Sub topic 8
Who owns the memory: opaque handles and allocation rules
This chapter assumes you know Rust ownership and Drop, can declare extern functions and call them in unsafe blocks, and know the C basics of malloc, free, and pointers. Here you decide who owns each piece of memory that crosses the boundary, and you encode that decision in Rust types.
The ownership question
Rust tracks ownership at compile time. C does not. A char * in a C header does not say whether you must free it, who frees it, or how long it stays valid. That information lives in the library's documentation, and the compiler cannot check it.
Every pointer that crosses the FFI boundary needs an answer to three questions:
- Who allocated it?
- Who must free it, and with which function?
- How long is it valid?
If you cannot answer all three from the C library's documentation or source, do not wrap the function yet.
Allocation rules
Follow these rules for every pointer.
- Free memory with the allocator that created it. Memory from C's
mallocmust go back throughfreeor the library's own free function. Memory from a RustBoxorCStringmust go back through Rust (Box::from_raw,CString::from_raw). Mixing them is undefined behavior. Rust's global allocator is not guaranteed to bemalloc, and a C library may use its own allocator or a different C runtime. - Prefer the library's own free function. If the library has
counter_free, call it. It may release more than one allocation. - Never free a borrowed pointer. If the C function returns a pointer into the library's internal state, you only borrow it. Freeing it is a double free later.
- Free exactly once. A second free is undefined behavior, and so is use after free.
| Pointer came from | You may | You must not |
|---|---|---|
| C function documented as "caller frees" | Free it with the documented function | Free it with Rust's allocator |
| C function documented as "valid until X" | Read it until X happens | Free it, or keep it after X |
| Rust (`Box::into_raw`, `CString::into_raw`) | Hand it to C to hold or read | Free it from C with `free` |
| Rust reference or `as_ptr()` | Let C read it during the call | Let C keep it after the call returns |
Opaque handles
Many C libraries hide their data behind an opaque handle. The header declares a type but not its fields, and you can only pass pointers to it:
typedef struct counter counter;
counter *counter_new(void);
int counter_increment(counter *c);
void counter_free(counter *c);Rust cannot see the fields, so it should not pretend to know them. Declare an empty type that exists only so pointers to it have a distinct type:
#[repr(C)]
pub struct RawCounter {
_private: [u8; 0],
}The zero-length array makes the type unconstructible by outside code in practice, and #[repr(C)] keeps it FFI-friendly. You only ever hold *mut RawCounter, never a RawCounter value. Using a distinct type per C handle also stops you from passing a counter * where a different handle type is expected.
Do not use *mut c_void for every handle. It compiles, but the compiler can no longer tell handle types apart.
Wrapping a handle with RAII
RAII means a value's constructor acquires a resource and its destructor releases it. Rust's Drop makes this a good match for C's create/destroy pairs. The wrapper type owns the handle, and the C free function runs when the wrapper goes out of scope.
use std::ffi::c_int;
use std::ptr::NonNull;
#[repr(C)]
pub struct RawCounter {
_private: [u8; 0],
}
// Assumed C API: counter *counter_new(void); int counter_increment(counter *); void counter_free(counter *);
unsafe extern "C" {
fn counter_new() -> *mut RawCounter;
fn counter_increment(c: *mut RawCounter) -> c_int;
fn counter_free(c: *mut RawCounter);
}
pub struct Counter {
raw: NonNull<RawCounter>,
}
impl Counter {
pub fn new() -> Option<Counter> {
NonNull::new(unsafe { counter_new() }).map(|raw| Counter { raw })
}
pub fn increment(&mut self) -> c_int {
unsafe { counter_increment(self.raw.as_ptr()) }
}
}
impl Drop for Counter {
fn drop(&mut self) {
unsafe { counter_free(self.raw.as_ptr()) }
}
}This wrapper makes several decisions:
newreturnsOption. C allocation functions return null on failure.NonNull::newturns null intoNone, so aCounternever holds a null pointer. Every other method can then skip null checks.incrementtakes&mut self. The C function mutates the counter, so the signature says so. Rust's borrow rules now stop two threads or two aliases from mutating it at once.Dropcallscounter_freeonce. Rust runsdropexactly once for each owned value. BecauseCounteris notCloneorCopy, no second owner can exist.- The type is neither
SendnorSync.NonNull<T>holds a raw pointer, so the compiler does not mark the wrapper thread-safe. That is the right default. Addunsafe impl Send for Counter {}only after the library's documentation says handles may move between threads.
Never derive Clone or Copy on a type that owns a handle. A copy would free the same pointer twice.
Borrowed pointers and lifetimes
Some C functions return a pointer into the handle's own storage. Suppose the library has const char *counter_name(const counter *c), and the docs say the string is valid until the counter is freed. Model that with a lifetime:
use std::ffi::{c_char, CStr};
// Continuing the Counter example. Assumed C API: const char *counter_name(const counter *c);
unsafe extern "C" {
fn counter_name(c: *const RawCounter) -> *const c_char;
}
impl Counter {
pub fn name(&self) -> &CStr {
unsafe { CStr::from_ptr(counter_name(self.raw.as_ptr())) }
}
}With lifetime elision, the returned &CStr borrows from &self. The borrow checker now rejects code that keeps the name after the Counter is dropped, which matches the C documentation. CStr::from_ptr assumes the pointer is non-null and null-terminated, so a function that can return null needs a check first.
If the library says the string is only valid until the next call that modifies the counter, the same signature is still correct for &self methods. Methods that mutate take &mut self, which cannot coexist with an outstanding &CStr.
Giving Rust memory to C
Sometimes C holds on to memory that Rust allocated, such as a string returned from a Rust function that C code calls. Convert the owner into a raw pointer so Rust stops tracking it, then take it back later:
use std::ffi::{c_char, CStr, CString};
#[unsafe(no_mangle)]
pub extern "C" fn greeting_new() -> *mut c_char {
CString::new("hello from Rust").unwrap().into_raw()
}
/// # Safety
/// `s` must be null or a pointer returned by `greeting_new` that has not been freed.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn greeting_free(s: *mut c_char) {
if !s.is_null() {
drop(unsafe { CString::from_raw(s) });
}
}
fn main() {
let s = greeting_new();
let text = unsafe { CStr::from_ptr(s) }.to_str().unwrap();
println!("{text}");
unsafe { greeting_free(s) };
}into_raw gives up ownership without freeing. from_raw rebuilds the CString so Rust can free it correctly. The pair must match: pointers from Box::into_raw go back through Box::from_raw, and pointers from CString::into_raw go back through CString::from_raw.
The C caller must use greeting_free. Calling free on this pointer would pass memory from Rust's allocator to C's, which is undefined behavior. from_raw also rebuilds the length from the terminator, so C code must not write a shorter or longer string into the buffer.
Lifetime of a handle
The diagram shows the states a wrapped handle moves through and where the wrapper blocks mistakes.
Common errors
- Freeing with the wrong allocator. Symptoms are crashes inside
free, or corruption that shows up later. Fix it by using the library's free function, orfrom_rawfor Rust-allocated memory. - Double free. This usually comes from
Clone/Copyon a wrapper, or from calling the free function manually and then dropping the wrapper. Keep the free call only inDrop. - Use after free. A borrowed pointer outlives its owner. Return references tied to
&selfinstead of raw pointers. - Leaking on early return. Raw pointers do not free themselves. A function that holds a raw pointer and returns early with
?leaks it. Put the pointer in the wrapper immediately after the C call returns. - Keeping a Rust pointer past the call.
CString::new("x").unwrap().as_ptr()in one expression gives C a pointer to a temporary that is dropped at the end of the statement. Bind theCStringto a variable that lives as long as C needs the pointer. - Assuming
NonNullmeans valid. It rules out null only. A dangling or already-freed pointer is still non-null.
Exercise
A C function char *make_label(int id) is documented as "returns a newly malloc'd string; the caller must free it with free". A teammate writes let s = unsafe { CString::from_raw(make_label(7)) }; and lets s drop at the end of the function. What is wrong, and how would you fix it?
Show answer
CString::from_raw assumes the memory came from Rust's allocator, so dropping s frees C-allocated memory with the wrong allocator, which is undefined behavior. Instead, read the string with CStr::from_ptr, copy it into an owned String (for example with to_string_lossy().into_owned()), and then call C's free (or the library's documented free function) on the original pointer. A wrapper type holding a NonNull<c_char> that calls free in Drop also works.
Exercise
Why does the Counter wrapper use NonNull<RawCounter> and make new return Option<Counter>, instead of storing *mut RawCounter and returning Counter directly?
Show answer
counter_new returns null when allocation fails. NonNull::new converts null into None, so a Counter value always holds a non-null pointer, and its methods and Drop never need to check for null. Returning Counter directly would either hide a null pointer inside the wrapper or require a panic on failure.
Exercise
Why must Counter not implement Clone or Copy?
Show answer
A clone or copy would hold the same raw pointer. Each owner's Drop would call counter_free on it, so the handle would be freed twice, which is undefined behavior. A wrapper that owns a unique C resource must have a single owner.