How does Box<T> alloc memory in heap?

this is a stupid doubt but ok, how Box heap a value in heap memory, i mean, the Box is a std implementation, how does std implement a heap alloc?

It uses GlobalAlloc trait implementation, which typically just forwards requests to libc's malloc.

4 Likes

Specifically, the #[global_allocator] is set by std[1] to std::alloc::System. Allocations use the global allocator's implementation of GlobalAlloc, which is implemented for System here (click the "Source" link).

(Implementation details, on Unix): System uses libc::malloc to allocate if the alignment returned from malloc would be sufficient, otherwise it falls back to posix_memalign. alloc_zeroed uses libc::calloc (if alignment permits, otherwise it allocates and then zeroes). dealloc always uses libc::free. realloc uses libc::realloc if possible, with a fallback to making a new allocation, copying, and freeing the old allocation.


  1. no_std crates can set their own global allocator ↩︎

6 Likes