4 ms·
In case of FFI, if C & Rust are using the same allocator (say the system allocator), does it mean that memory allocated by C can be freed by Rust and vice-versa
by sudeepj 8y ago
In case of FFI, if C & Rust are using the same allocator (say the system allocator), does it mean that memory allocated by C can be freed by Rust and vice-versa?
- sanxiyn 8y agoYes.
- dikaiosune 8y agoMany types in the standard library do not consider it sound behavior to have their allocations freed by functions other than their own destructors: https://doc.rust-lang.org/std/boxed/struct.Box.html#method.into_raw https://doc.rust-lang.org/std/boxed/struct.Box.html#method.i... After calling this function, the caller is responsible for the memory previously managed by the Box. In particular, the caller should properly destroy T and release the memory. The proper way to do so is to convert the NonNull<T> pointer into a raw pointer and back into a Box with the Box::from_raw function. I would guess that this might become a fun latent footgun in crates.io code -- everyone writes their unsafe code in a way that Just Works under the default allocator, but then things break down in confusing ways when enabling alternative allocators, which should be safe to do even when using external crates.
- steveklabnik 8y agoThat's already true in cases; for example, I've seen FFI code that has a use-after-free bug in it, but because of the different way that the allocator works on different platforms, on OS X it "worked", but on Linux, it segfaulted.
- dbaupp 8y agoThis is not safe in general, even within a single language. For instance, on Windows, it is essentially required that a pointer is freed by code from the dynamic library (even if they're both written in, say, C) that allocated it, because (IIRC) they could be using different versions of the platform allocator.