If I were to make two allocs using an example layout with size 256 and alignment 1024, I would expect the second allocation to be at the first multiple of 1024 after the first (ie ptr2 - ptr1 == 1024). Instead I am finding that there is a gap twice the size of 2048 bytes between the two allocs.
use std::alloc::alloc;
use std::alloc::Layout;
fn main() {
unsafe {
let size = 256;
let alignment = 1024
let large_layout = Layout::from_size_align_unchecked(size, alignment);
let ptr1 = alloc(large_layout) as usize;
let ptr2 = alloc(large_layout) as usize;
// I would expect this to print 1024, but it prints 2048...
println!("Difference1: {}", ptr2 - ptr1);
}
}
As I understand, the alignment makes it so that allocs only occur at multiples of the alignment, which does seem to be true, but it also seems like something else is going on. I know that an alloc also needs a word of space for the size of the alloc, which could explain in some cases why the gap might be larger than expected. However, in the case of size = 256, and alignment = 1024, there should be plenty of space between allocs allowing for them to be alloc'ed back to back? Here are some results of my experimentation between gaps of the pointers with different sizes and alignments. I'm confused at the examples where it seems that instead of rounding up to the nearest alignment, the gap is double what I expect.
| size | alignment | gap |
| ---- | --------- | ---- |
| 4 | 32 | 32 |
| 8 | 32 | 32 |
| 16 | 32 | 64 | ???
| 32 | 32 | 64 |
| ---- | --------- | ---- |
| 4 | 64 | 64 |
| 8 | 64 | 64 |
| 16 | 64 | 64 |
| 32 | 64 | 128 | ???
| 64 | 64 | 128 |
| ---- | --------- | ---- |
| 256 | 1024 | 2048 | ???
| 512 | 1024 | 2048 | ???
| 1024 | 1024 | 2048 |
| ---- | --------- | ---- |