mirror of
https://github.com/ziglang/zig.git
synced 2026-01-21 06:45:24 +00:00
Allocator.create: properly handle alignment for zero-sized types (#21864)
This commit is contained in:
parent
172dc6c314
commit
f391a2cd20
@ -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);
|
||||
|
||||
@ -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;
|
||||
}
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user