Zig 0.16.0: Init and arena

Given the new juicy main in zig v0.16.0, the runtime owns resources, not you, so you must not deinit(). Here’s what the arena property in std.process.Init struct looks like:

pub const Init = struct {
/// Permanent storage for the entire process,
/// cleaned automatically on exit.
arena: *std.heap.ArenaAllocator,
// ...
};
Init

As you see, arena is a pointer (*std.heap.ArenaAllocator), not a value. So you don’t own it, the runtime allocated it and passes you a pointer to it. It’s described as “permanent storage for the entire process, cleaned automatically on exit.” If you call arena.deinit(), you’d deinit() memory you don’t own, getting segfault.

const std = @import("std");
const Io = std.Io;

pub fn main(init: std.process.Init) !void {
var arena = init.arena;
const allocator = arena.allocator();
// arena.deinit() <-- don't!

var phone_book = std.AutoHashMap(i64, []const u8).init(allocator);
defer phone_book.deinit();

const one = "Foo";
const two = "Bar";
try phone_book.put(1, one);
try phone_book.put(2, two);

var iterator = phone_book.iterator();

while (iterator.next()) |obj| {
std.debug.print("{d}->{s}\n", .{ obj.key_ptr.*, obj.value_ptr.* });
}
}

// OUT:
// 1->Foo
// 2->Bar
Allocator

 

AdP

Archived: Zig