How to return allocated memory correctly?

Did I define the layout correctly?

fn drop(&mut self) {
    let layout = Layout::from_size_align(100 * size_of::<u32>(), align_of::<u32>()).unwrap();
    unsafe {
        dealloc(ptr as *mut u8, layout);
    }
}

Or is this variant correct? (differences only in align_of::<>() )

fn drop(&mut self) {
    let layout = Layout::from_size_align(100 * size_of::<u32>(), align_of::<u8>()).unwrap();
    unsafe {
        dealloc(ptr as *mut u8, layout);
    }
}

Thank you.

Use alloc to allocate memory, then use the same layout that you used for alloc to dealloc memory. What alignment you want depends on what you are doing with the allocation.

3 Likes

It looks like you are trying to have the layout of a [u32; 100]. In that case, as with any type known at compile time, you can get its layout with Layout::new::<[u32; 100]>().
In case 100 was just an example, and you actually have a dynamic length n (only known on runtime), then you need to replicate Layout::array::<u32>(n); which ends up being

Layout::from_size_align(n * size_of::<u32>(), align_of::<u32>()).unwrap()
  • (this uses the fact that size_of::<u32>() >= align_of::<u32>(), so that there is no stride in the allocated array)
2 Likes