1

I'm essentially looking for malloc/free in Rust.

I found alloc::heap, but when I try to use it I get the following error:

main.rs:1:1: 1:19 error: unstable feature                     
main.rs:1 ![feature(alloc)]
note: this feature may not be used in the stable release channel                                                                 

2 Answers 2

3

If you want to do it in high-level Rust (RAII, memory safety, bounds checking), you should allocate by creating a Vec. You can optionally use into_boxed_slice to disable resizing the container. See the book's FFI example (specifically the uncompress function) for an example of using Vec as an allocator.

Sign up to request clarification or add additional context in comments.

3 Comments

@xiver77 Vec is used as a defacto allocator though. Simply create a Vec<u8> with the desired size and then you can treat it as a slice or convert it to raw pointers.
@Shepmaster While I wonder what makes you call it "de facto", if you're going get the raw pointer from the storage and break the type system to do interesting things, why not just start with a raw pointer and raw memory. It's just my personal preference, though.
@xiver77 de facto means "in fact, or in effect, whether by right or not"; if people are using Vec as an allocator, I think it's appropriate to call it such. It's a stable way to allocate a chunk of memory that is built in to the standard library.
1

Either use a nightly Rust or you will have to use libc::funcs::c95::stdlib::malloc(size: size_t) from the libc crate. You'll have to transmute the result of course.

1 Comment

Note that there's no guarantee that malloc will use the same underlying allocator as the standard library, which uses jemalloc in most cases. So long as you never attempt to "cross the streams", having multiple allocators isn't likely to cause any issues in practice, but is good to know about.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.