Comment by josephg

Comment by josephg 8 days ago

3 replies

Yep. The right philosophy is to always put the allocation and deallocation code in the same language. If you create a struct with C, also make a destructor in C and call that from rust to destroy your object. (Usually by putting an ffi call in your drop impl).

And the same is true in reverse: rust struct might be temporarily owned and used by C code, but it should always be destroyed from rust.

Animats 6 days ago

> Yep. The right philosophy is to always put the allocation and deallocation code in the same language.

And on the same side of the API. Especially in Rust, he who allocates is responsible for deallocation. Rust's model likes that symmetry.

This example looks like someone going to considerable trouble to create a footgun, then shooting themself with it. More likely, this example exists because they're using some C library with terrible memory semantics, and this is a simple example to illustrate a problem they had with a badly designed real library.

flohofwoe 8 days ago

It's also a bad idea within the same language.

A C library returning a pointer to allocated memory and then expecting the caller to free that memory with a function outside the library (like calling stdlib free()) is just bad API design (because you can't and shouldn't need to know whether the library is actually using the stdlib alloc functions under the hood - or whether the library has been linked with the same C stdlib than your own code - for instance when the library resides in a DLL, or the library might decide to bypass malloc and directly use lower-level OS calls for allocating memory).

If you have a 'create' function in a C library, also always have a matching 'destroy' function.

On top of that it's also usually a good idea to let the library user override things like memory allocation or file IO functions.

...and of course 'general purpose' global allocators are a bad idea to begin with :)

  • filmor 8 days ago

    That is exactly what what the parent post proposed.