#malloc #free #ffi #box #cstr

no-std mbox

malloc-based box. Supports wrapping pointers or null-terminated strings returned from malloc as a Rust type, which will be free'd on drop

13 releases

Uses old Rust 2015

0.6.0 Mar 31, 2021
0.5.0 Apr 10, 2018
0.4.4 May 17, 2018
0.4.3 Feb 5, 2018
0.1.2 Jul 5, 2016

#855 in Rust patterns

Download history 3157/week @ 2023-11-03 3164/week @ 2023-11-10 1821/week @ 2023-11-17 2471/week @ 2023-11-24 2245/week @ 2023-12-01 2145/week @ 2023-12-08 1853/week @ 2023-12-15 901/week @ 2023-12-22 1715/week @ 2023-12-29 2053/week @ 2024-01-05 2362/week @ 2024-01-12 2868/week @ 2024-01-19 2163/week @ 2024-01-26 2588/week @ 2024-02-02 1873/week @ 2024-02-09 1972/week @ 2024-02-16

9,048 downloads per month
Used in 15 crates (2 directly)

MIT license

1.5K SLoC

mbox: malloc-based box

Crates.io docs.rs Build status MIT

This crate provides structures that wrap pointers returned from malloc as a Box, and automatically free them on drop. These types allow you to interact with pointers and null-terminated strings and arrays in a Rusty style.


extern crate libc;
extern crate mbox;

use libc::{c_char, malloc, strcpy};
use mbox::MString;

// Assume we have a C function that returns a malloc'ed string.
unsafe extern "C" fn create_str() -> *mut c_char {
    let ptr = malloc(12) as *mut c_char;
    strcpy(ptr, b"Hello world\0".as_ptr() as *const c_char);

fn main() {
    // we wrap the null-terminated string into an MString.
    let string = unsafe { MString::from_raw_unchecked(create_str()) };

    // check the content is expected.
    assert_eq!(&*string, "Hello world");

    // the string will be dropped by `free` after the code is done.


Add this to your Cargo.toml:

mbox = "0.6"


This crate provides three main types, all of which uses the system's malloc/free as the allocator.

  • MBox<T> — Similar to Box<T>.
  • MString — Similar to std::ffi::CString.
  • MArray<T> — A null-terminated array, which can be used to represent e.g. array of C strings terminated by a null pointer.


You may compile mbox and disable the std feature to not link to std (it will still link to core.

mbox = { version = "0.6", default-features = false }

When #![no_std] is activated, you cannot convert an MString into a std::ffi::CStr, as the type simply does not exist 🙂.

Migrating from other crates

Note that MBox does not support custom allocator. If the type requires custom allocation, MBox cannot serve you.

  • malloc_bufMallocBuffer<T> is equivalent to MBox<[T]>. Note however we will not check for null pointers.

  • cbox — When not using a custom DisposeRef, the CSemiBox<'static, T> type is equivalent to MBox<T>, and CBox<T> is equivalent to &'static T.

  • c_vec — When using free as the destructor, CVec<T> is equivalent to MBox<[T]> and CSlice<T> as [T].