Hi, Rust fans,
I am using a C library via FFI. On the C side, it uses
malloc to allocate heap memory and returns a raw pointer. Then on the Rust side, I need to create a
Vec using this pointer.
I want to use
Vec::from_raw_parts because it also transfers the ownership of the heap memory to Rust, so I don't need to manually call
However, many posts said that memory allocated in C should not be freed by Rust, since C and Rust may use different memory allocators.
A Rust vector must be allocated by Rust. You can't turn malloc'ed arrays into a Vec. Allocate the memory in Rust.
You can't take data pointer from C and return it to Rust as Vec. Only Rust can allocate a Vec, because it's always freed using Rust's own private allocator. If you want to return a Vec, you'll have to copy the data into it first.
CVec for allowing Rust to use malloc-allocated data.
&[u8] is a type that means "you never ever have to worry about freeing it", so you can return it from a function only as &'static [u8] if C leaked that memory or it's from a global/static variable in C, but …
To my understanding, this was indeed unsafe in the past because Rust used jemalloc. But nowadays Rust uses the system allocator by default.
My question is, nowadays is it safe to free heap memory allocated by
malloc in Rust?
Thank you very much!
It's quite possible that it works if you try, but it's not considered ok.
the ability to replace the global allocator, it's definitely wrong to do this in library code that might be used in multiple projects. Similarly, Rust may change its default allocator in future versions, and
malloc interoperation isn't guaranteed in the future, even if it works now.
might be acceptable to do this if you explicitly override Rust's default allocator in your project with a custom one designed for interoperation.
Vec now also has an
Allocator type parameter, so you will eventually be able to use
instead of replacing the global allocator.
Thanks. Yes, I tried several toy examples and I didn't observe any problems.
Just want to know if there are any other security concerns besides memory allocators.
Didn't notice this
Vec::from_raw_parts_in API before. Thank you very much!
This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.