How to free slices with default values? [ZON]

const std = @import("std");

const Config = struct { name: []const u8 = "default" };

pub fn main() !void {
    var gpa = std.heap.GeneralPurposeAllocator(.{}){};
    defer if (gpa.deinit() == .leak) @panic("leak!");

    const parsed = std.zon.parse.fromSlice(
        Config,
        gpa.allocator(),
        ".{}",
        null,
        .{},
    ) catch unreachable;
    std.zon.parse.free(gpa.allocator(), parsed);
}

This code will panic on free because “default” string is not allocated on heap.

Removing default value is not a solution because I really need it.

Thank on advance.

P.S.: Zig version is 0.15.0-dev.451+a843be44a.

You can use a temporary arena:

var arena = std.heap.ArenaAllocator.init(gpa.allocator());
const parsed = ...(..., arena.allocator(), ...);
arena.deinit(); // Frees anything allocated above, no need to call std.zon.parse.free()
3 Likes

Perfect, thank you.

Just one (maybe silly) question: how mush overhead has ArenaAllocator compare to plain Allocator?

It’ll add some simple conditional logic and function pointer calls.

However, since ArenaAllocator doesn’t need to worry about random freeing, it can allocate by resizing existing allocations with the backing allocator rather than making a new allocation every time. This can be a lot more performant, depending on the backing allocator.

1 Like