I am new to systems programming and just trying to better understand what is happening. I made this little experiment to better understand what happens when a zig allocator runs out of memory, but I don't really understand why one crashes and the other does not. does anyone have advice for how to handle system out of memory without the program crashing, or an explanation on why that is not possible to do?
I am developing on pop-os 22.04 and using zig version 0.11.0-dev.1457+cb9d00e1a.
// this fails with exit code 1
pub fn main() !void {
var arena_allocator = std.heap.ArenaAllocator.init(std.heap.page_allocator);
var allocator = arena_allocator.allocator();
var is_memory_available = true;
while (is_memory_available) {
_ = allocator.alloc(u8, 1024) catch |err| {
std.debug.print("error: {}\n", .{err});
is_memory_available = false;
arena_allocator.deinit();
};
}
std.debug.print("done\n", .{});
}
// this works fine, it prints out there error and then prints "done"
pub fn main() !void {
var heap_buffer: [4096]u8 = undefined;
var fixed_buffer_allocator = std.heap.FixedBufferAllocator.init(&heap_buffer);
var fixed_allocator = fixed_buffer_allocator.allocator();
var arena_allocator = std.heap.ArenaAllocator.init(fixed_allocator);
var allocator = arena_allocator.allocator();
var is_memory_available = true;
while (is_memory_available) {
_ = allocator.alloc(u8, 1024) catch |err| {
std.debug.print("error: {}\n", .{err});
is_memory_available = false;
arena_allocator.deinit();
};
}
std.debug.print("done\n", .{});
}