Sub topic 8
Who Owns the Memory: Opaque Handles and Allocation Rules
This chapter assumes you can write basic Rust (ownership, Drop, Option), know C pointers and malloc/free, and have already declared and called C functions in unsafe blocks. It covers the part of FFI that causes the most crashes: deciding who frees each piece of memory.
Ownership lives in documentation
C has no ownership types. A counter * could be borrowed, owned, or shared, and only the library's documentation says which. Before you write any Rust, find the rule for every pointer that crosses the boundary.
| Situation | Who frees it | Rust side |
|---|---|---|
| C allocates and returns a pointer | C's matching free function | Wrapper type with `Drop` |
| Rust allocates and passes a pointer | Rust | Borrow it for the call only |
| C returns a pointer into its own data | The C owner, later | Borrow, with a lifetime tied to the owner |
| C takes ownership of a pointer you pass | C | Transfer it with `into_raw` and never touch it again |
The core rule is to free memory with the allocator that produced it. Rust's allocator and C's malloc may differ, so mixing them is undefined behavior.
Opaque handles
Many C libraries hide their structs behind a pointer. The header declares typedef struct counter counter; and never shows the fields. Rust models this with an empty #[repr(C)] struct. You only ever hold pointers to it, never values.
A wrapper that owns the handle
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()) }
}
}The C API in the comment is hypothetical, so this code compiles only when you link a library that provides those functions. Each design choice maps to a rule:
counter_newreturns null on failure.NonNull::newturns that intoNone, so aCounternever holds a null pointer.Counterdoes not implementCloneorCopy. Two owners of one handle would free it twice.incrementtakes&mut self. Rust's borrow rules now enforce exclusive access, which the C library probably assumes.Dropruns once when the value goes out of scope, so the handle is freed exactly once, even on early returns.NonNullmakesCounterneitherSendnorSync. Addunsafe impl Sendonly if the C documentation says the handle may move between threads.
Common mistakes
- Dangling temporary. In
CString::new("x").unwrap().as_ptr(), theCStringis dropped at the end of the statement, so the pointer dangles. Bind theCStringto a variable that outlives the call. - Wrong free function. Calling
freeon memory fromcounter_new, orcounter_freeon memory from Rust'sBox, corrupts the heap. Use the matching pair. - Leaking by
into_raw.Box::into_rawandCString::into_rawgive up Rust's ownership. Take the memory back withfrom_rawto free it. Do not pass it to C'sfree. - Keeping borrowed pointers. If C returns a pointer into a handle's data, tie the Rust reference to a borrow of the wrapper. Otherwise it can outlive
counter_free.
Exercise
A C function char *make_name(void) returns a string allocated with malloc, and the library also provides void free_name(char *). Which function should the Rust wrapper's Drop call, and why not Rust's own deallocation?
Show answer
It should call free_name. The memory came from C's allocator, and the library's free function is the documented way to release it. Rust's allocator may differ from C's, so releasing the memory through Rust, for example by building a Box or String from the pointer, is undefined behavior.