How could I check if my memory allocation is correct?

Viewed 417

I'm trying to do my own memory allocation with the alloc crate. The way I implemented it, and if I understand how the Layout works, the below line should get the size I want to allocate in bytes as the first argument, and a value to round to for the second. So in my example, I would like to allocate 20 bytes, which will be rounded to 4096 since I passed it that value. Then alloc will allocate that memory and return a pointer to the start of my allocation.

let pr = alloc(Layout::from_size_align(20, 4096).unwrap());

Is my understanding of the functionality correct? Also, is there any way to check if the number of bytes specified have been allocated or not?

1 Answers

Alignment is not about rounding the size of an allocation. Instead it has to do with the integer value of the pointer that points to the start of the allocation in the sense that this pointer must be a multiple of the alignment.

let pr = alloc(Layout::from_size_align(size, align).unwrap());
assert!(pr as usize % align == 0);

If you want to round-up the size of an allocation to the next multiple of 4096, you can do this:

let rounded_size = (size + 4095) / 4096;

If you ask for a size of 20 bytes, your allocation will only be 20 bytes large, and if you want an allocation of 4096 bytes, you should allocate 4096 bytes.


When choosing an alignment for your data, you should consider what types will be stored in the allocation. This is because certain types require a certain minimum alignment, e.g. an u32 must have an alignment of at least 4.

If all you are storing in the memory is u8 bytes, then an alignment of 1 is fine. If you need to store an u16, you need an alignment of 2. If you need to store an u32 you need 4 and u64 requires 8. If you have multiple of them, you should pick the largest alignment that one of the types require, e.g. if you store u8, u32 and u64s in the data, pick the alignment 8.

You can compute the minimum allowed alignment for a type using align_of.

Related