Hi, even if I have basic knowledge in memory alignment I struggle to understand why only the first block fails at runtime:
pub fn main(init: std.process.Init) !void {
const alloc = init.arena.allocator();
{ // Panics
_ = alloc.alloc(u8, 2) catch unreachable;
const b = alloc.alloc(u8, @sizeOf(i32)) catch unreachable;
// Panics on next line at runtime with: 'thread 8300 panic: incorrect alignment'
@as(*i32, @ptrCast(@alignCast(b))).* = 5;
}
{ // Runs fine because I allocated 32bits, same size as `i32`?
_ = alloc.alloc(u8, 4) catch unreachable;
const b = alloc.alloc(u8, @sizeOf(i32)) catch unreachable;
@as(*i32, @ptrCast(@alignCast(b))).* = 5;
}
{ // Runs fine because I used `alignedAlloc` (and no need for `@alignCast`)
_ = alloc.alloc(u8, 2) catch unreachable;
const b = alloc.alignedAlloc(u8, .of(i32), @sizeOf(i32)) catch unreachable;
@as(*i32, @ptrCast(b)).* = 5;
}
}
Do memory allocations have to respect alignment when using same allocator for various sizes like in this example?