authorgravatar for goon.pri.low@gmail.comKendall Condon <goon.pri.low@gmail.com> 2025-03-26 11:31:57-04:00
committergravatar for alex@alexrp.comAlex Rønne Petersen <alex@alexrp.com> 2025-03-26 21:52:12+01:00
logf391a2cd2075855a1b179eaef9facbdd539b4b8a
tree0451010582e0268e785045c8fa3b4246eebffc6f
parent172dc6c3143b22802a64208f371d4dba1b90927e
signaturebadge-check Signed by SSH key SHA256:7B/LJ7bpR1eX8aCXSr4mtd5M45VMPKcx9zY8e95b5QM

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


2 files changed, 6 insertions(+), 1 deletions(-)

lib/std/heap.zig+2
......@@ -593,6 +593,8 @@ pub fn testAllocator(base_allocator: mem.Allocator) !void {
593593 const zero_bit_ptr = try allocator.create(u0);
594594 zero_bit_ptr.* = 0;
595595 allocator.destroy(zero_bit_ptr);
596 const zero_len_array = try allocator.create([0]u64);
597 allocator.destroy(zero_len_array);
596598
597599 const oversize = try allocator.alignedAlloc(u32, null, 5);
598600 try testing.expect(oversize.len >= 5);
lib/std/mem/Allocator.zig+4-1
......@@ -150,7 +150,10 @@ pub inline fn rawFree(a: Allocator, memory: []u8, alignment: Alignment, ret_addr
150150/// Returns a pointer to undefined memory.
151151/// Call `destroy` with the result to free the memory.
152152pub fn create(a: Allocator, comptime T: type) Error!*T {
153 if (@sizeOf(T) == 0) return @as(*T, @ptrFromInt(math.maxInt(usize)));
153 if (@sizeOf(T) == 0) {
154 const ptr = comptime std.mem.alignBackward(usize, math.maxInt(usize), @alignOf(T));
155 return @as(*T, @ptrFromInt(ptr));
156 }
154157 const ptr: *T = @ptrCast(try a.allocBytesWithAlignment(@alignOf(T), @sizeOf(T), @returnAddress()));
155158 return ptr;
156159}