rust-ffi-guide icon indicating copy to clipboard operation
rust-ffi-guide copied to clipboard

Beware of allocators mismatch

Open fabricedesre opened this issue 6 years ago • 2 comments

When eg. you get a buffer allocated from the C side of the FFI and are expected to manage its lifetime in Rust, extra care needs to happen in the Rust code to deallocate with the C malloc/free and not just drop it since Rust is using jemalloc.

The same precautions need to be taken when handing buffers to the C side.

I've found it needed to write small custom functions to expose deallocation or allocation missing on the C side to make that clear and correct.

fabricedesre avatar Nov 04 '17 18:11 fabricedesre

This sounds like a nice way to shoot yourself in the foot by messing up the allocator's internal bookkeeping. I imagine the solution for this problem would mention that a good rule of thumb is to always deallocate something from the language that allocated it. That's what I've done in all the FFI bindings I've done at work.

I think another best practice is to avoid passing ownership between languages if possible. So for example, say you are wanting to pass the contents of a std::vector from C++ to Rust, you'd instead pass a pointer to the first element and the number of elements. Effectively only passing borrowed slices between languages.

Something else to note is that Rust will use the system allocator if it is compiled as a cdylib. So technically you could probably get away with using drop(), but I wouldn't recommend it.

Michael-F-Bryan avatar Nov 05 '17 06:11 Michael-F-Bryan

I've posted this issue on the [TWIR] Call for Participation thread on the user forums.

Michael-F-Bryan avatar Nov 05 '17 07:11 Michael-F-Bryan