Is it safe to free memory allocated by `malloc` in Rust?

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 free.

However, many posts said that memory allocated in C should not be freed by Rust, since C and Rust may use different memory allocators.

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.


Given 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.

It 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 Vec::from_raw_parts_in 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.