From de82444ac327c6340a11f38080e74053d820da27 Mon Sep 17 00:00:00 2001 From: kayomn Date: Mon, 29 May 2023 01:22:30 +0000 Subject: [PATCH] Fix segfault when allocating zero-length memory --- source/coral/io.zig | 4 ---- source/ona/heap.zig | 12 ++++++++++-- 2 files changed, 10 insertions(+), 6 deletions(-) diff --git a/source/coral/io.zig b/source/coral/io.zig index 9437ebf..c955141 100755 --- a/source/coral/io.zig +++ b/source/coral/io.zig @@ -143,10 +143,6 @@ pub fn allocate_many(comptime Type: type, amount: usize, allocator: Allocator) A @compileError("Cannot allocate memory for 0-byte type " ++ @typeName(Type)); } - if (amount == 0) { - return &.{}; - } - return @ptrCast([*]Type, @alignCast(@alignOf(Type), allocator.invoke(.{.size = @sizeOf(Type) * amount}) orelse { return error.OutOfMemory; }))[0 .. amount]; diff --git a/source/ona/heap.zig b/source/ona/heap.zig index 14cfd1a..25923f0 100644 --- a/source/ona/heap.zig +++ b/source/ona/heap.zig @@ -7,15 +7,23 @@ const Context = struct { const Self = @This(); + const empty_allocation = [0]u8{}; + fn reallocate(self: *Self, options: coral.io.AllocationOptions) ?[]u8 { if (options.size == 0) { if (options.allocation) |allocation| { - ext.SDL_free(allocation.ptr); + if (allocation.ptr != &empty_allocation) { + ext.SDL_free(allocation.ptr); + } self.live_allocations -= 1; + + return null; } - return null; + self.live_allocations += 1; + + return &empty_allocation; } if (options.allocation) |allocation| {