Commit b4b1daf001

Kendall Condon <149842806+gooncreeper@users.noreply.github.com>
2025-03-26 16:31:57
Allocator.create: properly handle alignment for zero-sized types (#21864)
1 parent b84db31
Changed files (2)
lib/std/mem/Allocator.zig
@@ -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;
 }
lib/std/heap.zig
@@ -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);