Skip to content

Commit b4b1daf

Browse files
authored
Allocator.create: properly handle alignment for zero-sized types (#21864)
1 parent b84db31 commit b4b1daf

File tree

2 files changed

+6
-1
lines changed

2 files changed

+6
-1
lines changed

lib/std/heap.zig

+2
Original file line numberDiff line numberDiff line change
@@ -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
Original file line numberDiff line numberDiff line change
@@ -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.
152152
pub 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
}

0 commit comments

Comments
 (0)