Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

why does allocate() use `[u8]` while deallocate uses `u8` in Allocator API?

    fn allocate(&self, layout: Layout) -> Result<NonNull<[u8]>, AllocError>;
    unsafe fn deallocate(&self, ptr: NonNull<u8>, layout: Layout);

from https://doc.rust-lang.org/std/alloc/trait.Allocator.html

I also note that in contrast, GlobalAlloc uses *mut u8 consistently https://doc.rust-lang.org/std/alloc/trait.GlobalAlloc.html

    unsafe fn alloc(&self, layout: Layout) -> *mut u8;
    unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout);

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Note that this it is not decided yet what will be the final shape of this code, and it may change.


deallocate() takes NonNull<u8> because to deallocate memory you don’t need more than that. Only that pointer to the start of the allocation.

But for allocate(), allocators may over-allocate for various reasons. When they do that, it will be nice to inform the user that they over-allocated and how much. For example, a Vec may use this information to grow more than it initially wanted to, if the memory is available anyway.

This is why allocate() returns NonNull<[u8]>, to inform the caller what is the actual size of the allocation.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading