mimalloc_rust icon indicating copy to clipboard operation
mimalloc_rust copied to clipboard

Expose dealloc function that doesn't require `Layout`?

Open rtfeldman opened this issue 2 years ago • 3 comments

Thanks for making this!

I notice the dealloc function takes an unused _layout parameter (in order to satisfy the allocator trait, which makes sense) - but I have a use case where I'd like to call a version of that function that doesn't require being passed a layout at all (because I'll be calling it directly and won't have access to the layout when I'm calling it).

I could always call the current dealloc passing an empty layout, since I know that it's currently unused, but it would be risky for me to rely on that assumption; it seems pretty likely that I could get some really bad behavior if that argument somehow stopped being unused in a future release of the crate, and I wouldn't even get a compiler error!

If this is a design you're open to, I'd be happy to contribute a PR for it!

rtfeldman avatar Sep 28 '23 03:09 rtfeldman

Why not use mi_free from the -sys crate directly in that case? The wrapper would need to be unsafe anyways.

nathaniel-daniel avatar Sep 30 '23 00:09 nathaniel-daniel

Note that dealloc is provided by the GlobalAlloc trait, it's interface is outside of this crate's control.

Also note that even if you know mimalloc is the #[global_allocator], mi_freeing a pointer allocated by from the rust global allocator (e.g. allocated with std::alloc::alloc) isn't guaranteed to be defined behavior (I believe LLVM would consider it UB).

thomcc avatar Sep 30 '23 00:09 thomcc

Also note that even if you know mimalloc is the #[global_allocator], mi_freeing a pointer allocated by from the rust global allocator (e.g. allocated with std::alloc::alloc) isn't guaranteed to be defined behavior (I believe LLVM would consider it UB).

Interesting, do you have more info on that? The docs seem to suggest std::alloc::alloc just forwards to GlobalAlloc's alloc method, which would return a pointer that was allocated by mimalloc. If it is known that the global allocator is mimalloc, would it not then be safe to free with mi_free, since the std::alloc::dealloc would just forward to the GlobalAlloc's dealloc? Or do you mean the docs don't actually promise that they just forward the pointer to the global allocator?

Note that dealloc is provided by the GlobalAlloc trait, it's interface is outside of this crate's control.

I think what is being asked for is a separate function on the MiMalloc struct that can free without a layout. Not sure how good of an idea it is to promote freeing without a layout though.

nathaniel-daniel avatar Sep 30 '23 00:09 nathaniel-daniel