Allocator.create: properly handle alignment for zero-sized types (#21864)

This commit is contained in:
Kendall Condon 2025-03-26 11:31:57 -04:00 committed by Alex Rønne Petersen
parent 172dc6c314
commit f391a2cd20
No known key found for this signature in database
2 changed files with 6 additions and 1 deletions

View File

@ -593,6 +593,8 @@ pub fn testAllocator(base_allocator: mem.Allocator) !void {
const zero_bit_ptr = try allocator.create(u0);
zero_bit_ptr.* = 0;
allocator.destroy(zero_bit_ptr);
const zero_len_array = try allocator.create([0]u64);
allocator.destroy(zero_len_array);
const oversize = try allocator.alignedAlloc(u32, null, 5);
try testing.expect(oversize.len >= 5);

View File

@ -150,7 +150,10 @@ pub inline fn rawFree(a: Allocator, memory: []u8, alignment: Alignment, ret_addr
/// Returns a pointer to undefined memory.
/// Call `destroy` with the result to free the memory.
pub fn create(a: Allocator, comptime T: type) Error!*T {
if (@sizeOf(T) == 0) return @as(*T, @ptrFromInt(math.maxInt(usize)));
if (@sizeOf(T) == 0) {
const ptr = comptime std.mem.alignBackward(usize, math.maxInt(usize), @alignOf(T));
return @as(*T, @ptrFromInt(ptr));
}
const ptr: *T = @ptrCast(try a.allocBytesWithAlignment(@alignOf(T), @sizeOf(T), @returnAddress()));
return ptr;
}