Fix segfault when allocating zero-length memory

This commit is contained in:
kayomn 2023-05-29 01:22:30 +00:00
parent 1fb5fc6048
commit de82444ac3
2 changed files with 10 additions and 6 deletions

View File

@ -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)); @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 @ptrCast([*]Type, @alignCast(@alignOf(Type), allocator.invoke(.{.size = @sizeOf(Type) * amount}) orelse {
return error.OutOfMemory; return error.OutOfMemory;
}))[0 .. amount]; }))[0 .. amount];

View File

@ -7,15 +7,23 @@ const Context = struct {
const Self = @This(); const Self = @This();
const empty_allocation = [0]u8{};
fn reallocate(self: *Self, options: coral.io.AllocationOptions) ?[]u8 { fn reallocate(self: *Self, options: coral.io.AllocationOptions) ?[]u8 {
if (options.size == 0) { if (options.size == 0) {
if (options.allocation) |allocation| { if (options.allocation) |allocation| {
ext.SDL_free(allocation.ptr); if (allocation.ptr != &empty_allocation) {
ext.SDL_free(allocation.ptr);
}
self.live_allocations -= 1; self.live_allocations -= 1;
return null;
} }
return null; self.live_allocations += 1;
return &empty_allocation;
} }
if (options.allocation) |allocation| { if (options.allocation) |allocation| {