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?
answer
- the allocator that allocated
- a Drop that calls the library
- into_raw has a partner
- never C's free on Rust memory
basics
~20 sWhoever 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.
solid answer
~40 sThe rule is that memory goes back to the allocator that produced it. A buffer `kz_compress` allocated belongs to the C library, so the Rust wrapper stores the pointer in a type like `KzBuffer` whose `Drop` calls `kz_free` exactly once. It never builds a `Vec` or `Box` from it, because those would release it through Rust's global allocator. In the other direction, a string Rust returns via `CString::into_raw` must come back to Rust: export `kz_string_free`, which calls `CString::from_raw` and drops the result. The `into_raw` docs say C's `free()` must not be used, and Miri reports such a call as undefined behaviour. C also must not change the string's length before returning it, since `from_raw` recomputes the length with `strlen`. Strings C only *borrows* for a call need no transfer at all.
code
rust · 37 linesuse std::ffi::{c_int, c_void};
type ProgressFn = extern "C" fn(*mut c_void, usize, usize) -> c_int;
unsafe extern "C" {
fn kz_compress(src: *const u8, len: usize, out: *mut *mut u8, out_len: *mut usize,
progress: Option<ProgressFn>, ctx: *mut c_void) -> c_int;
fn kz_free(buf: *mut u8);
}
/// A buffer the C library allocated; only kz_free may release it.
pub struct KzBuffer { ptr: *mut u8, len: usize }
impl KzBuffer {
pub fn as_slice(&self) -> &[u8] {
// SAFETY: ptr and len come from a successful kz_compress and are not freed yet.
unsafe { std::slice::from_raw_parts(self.ptr, self.len) }
}
}
impl Drop for KzBuffer {
fn drop(&mut self) {
// SAFETY: the library allocated ptr, so its own free function releases it, once.
unsafe { kz_free(self.ptr) }
}
}
pub fn compress(src: &[u8]) -> Result<KzBuffer, c_int> {
let (mut ptr, mut len) = (std::ptr::null_mut(), 0);
// SAFETY: src is valid for src.len() bytes; ptr and len are valid for writes.
let rc = unsafe { kz_compress(src.as_ptr(), src.len(), &mut ptr, &mut len, None, std::ptr::null_mut()) };
if rc == 0 { Ok(KzBuffer { ptr, len }) } else { Err(rc) }
}
fn main() {
let out = compress(&[7u8; 64]).expect("compress failed");
println!("{} bytes", out.as_slice().len());
} // out dropped here: kz_free runs exactly oncego deeper
Recall the rule that whoever allocates frees, with the matching function, and that C's free must never touch Rust-allocated memory.
Explain into_raw and from_raw as a pair, why C must not change the length, and why CStr::from_ptr borrows without freeing.
Design the wrapper: owning types whose Drop calls the library's free exactly once, exported free functions for every into_raw, borrows tied to lifetimes. Know what Miri can and cannot check here.
Make ownership part of the API contract: every returned pointer documented as owned, borrowed or static, and one release function per allocation kind, checked in review.
## The one rule: the allocator that allocated, frees Rust and C each manage heap memory through an **allocator**. Rust's global allocator serves `Box`, `Vec`, `String` and `CString`; the C library uses `malloc` or its own pool. They may be the same underlying `malloc` on some platforms, but nothing guarantees it. The global allocator can be replaced, a C library can use an arena, and a DLL on Windows can have its own C runtime heap. So the portable rule is: - memory is released by the **same allocator** that allocated it, - through the **owner's documented function**, - **exactly once**. Breaking it is undefined behaviour, not a leak. Miri, when it can see both sides, reports it plainly: `deallocating alloc309, which is Rust heap memory, using C heap deallocation operation`. ## Direction 1: C allocates, Rust frees through C A typical C API returns a buffer through an out-parameter and documents a free function: ```c int kz_compress(const unsigned char *src, size_t len, unsigned char **out, size_t *out_len, kz_progress_fn progress, void *ctx); void kz_free(unsigned char *buf); ``` The sound Rust wrapper: 1. calls `kz_compress` with pointers to local `ptr` and `len` variables; 2. on success, moves them into an owning type such as `KzBuffer { ptr, len }`; 3. lends the data out as `&[u8]` through `slice::from_raw_parts`, tied to `&self`; 4. implements `Drop` to call `kz_free(self.ptr)`. Ownership is then tracked by the type system. Moves, early returns and `?` all end in exactly one `kz_free`, unless someone deliberately leaks the value with `mem::forget`. Two tempting shortcuts are both wrong: | Shortcut | Why it is wrong | |---|---| | `Vec::from_raw_parts(ptr, len, len)` | the `Vec` frees with Rust's allocator, which did not allocate the buffer | | `CString::from_raw(ptr)` on a C string | its docs say other usage, such as taking ownership of a string allocated by foreign code, is likely to lead to undefined behaviour or allocator corruption | If you need an owned Rust value, copy: `buf.as_slice().to_vec()`, then let `KzBuffer` drop. ## Direction 2: Rust allocates, C must give it back When Rust returns a heap string to C, `CString::into_raw` hands over ownership as a `*mut c_char` and stops Rust from freeing it. The documentation then sets three conditions: - The pointer **must be returned to Rust** and rebuilt with `CString::from_raw` to be deallocated. C's `free()` must not be used. - Failing to call `from_raw` **leaks** the string. - The C side **must not change the length** by writing a NUL inside the string or removing the final one. `from_raw` recomputes the length with `strlen`, and that length must match the original allocation. So the library exports a pair of functions: a producer like `kz_describe` that returns `into_raw()`, and `kz_string_free` that calls `CString::from_raw` and drops it. The header documents that the producer's result is released only by `kz_string_free`. Making the free function accept null and do nothing matches what C programmers expect from `free`. For opaque objects (a Rust compressor state behind a `kz_ctx *`), the same pattern applies with `Box::into_raw` and `Box::from_raw`. The details of that API belong to the material on `Box`. ## Borrowing needs no transfer Not every pointer crossing the boundary moves ownership: - Rust passing `c_name.as_ptr()` to a C function that only reads it during the call: Rust keeps ownership, and the `CString` just has to outlive the call. - C passing a `const char *` into a Rust export: wrap it with `CStr::from_ptr`, read or copy it, and never free it. - C returning a pointer to its own static data, such as an error-message table: borrow it with `CStr::from_ptr`, copy it with `to_string_lossy().into_owned()`, and free nothing. The C documentation decides which case applies. Phrases like "caller must free", "owned by the context" or "valid until the next call" are what you encode in the wrapper's types. ## Checklist for a review - Every pointer returned by C maps to a Rust type with exactly one release path, or to a borrow with a lifetime. - Every `into_raw` has a documented, exported partner that calls `from_raw`. - No `Vec`, `Box`, `String` or `CString` is ever rebuilt from memory the other side allocated. - Run the Rust-only parts under Miri. Miri cannot execute foreign C functions it has no shim for, so the C side needs a native tool, such as a sanitizer build.
- Why not just tell C callers to use `free()` on strings Rust returns, since Rust usually uses `malloc` underneath?Nothing guarantees it. The global allocator can be swapped with `#[global_allocator]`, and on some platforms each library has its own C runtime heap. The `into_raw` documentation forbids C's `free()` outright, and Miri flags the mix as undefined behaviour. Exporting a matching free function costs one line and removes the question.
- How do you return a byte buffer, not a string, from Rust to C and free it later?Convert the `Vec<u8>` into a `Box<[u8]>`, hand out `Box::into_raw` as pointer plus length, and export a free function that rebuilds the box from both and drops it. Either way, Rust's allocator frees what Rust allocated.
Returning a rental car to the company you rented it from: another company's lot will not take it back, even if the car looks the same, and leaving it at the wrong lot causes trouble for everyone.
- C's free() can release a CString::into_raw pointer.
- Vec::from_raw_parts is a fine way to take over a C buffer.
- CStr::from_ptr takes ownership and frees the string on drop.
- A buffer freed by the wrong allocator only leaks.
- C may shorten a Rust string in place before returning it.