liveBook · Manning

Arena

As explained in Systems Programming with Zig

Arena allocation obtains storage from an arena and typically releases the storage collectively rather than freeing individual allocations.

An arena allocator groups allocations so they can be released together. Instead of tracking every small allocation, give the group a shared lifetime and clean it up when that lifetime ends. section 5.3.2 section 3.4.2

Recipe strings that live together

A recipe book stores names, authors, instructions, and ingredient strings in a single arena. Those strings can live as long as the recipe book, without a separate free for each one. The book initializes its std.heap.ArenaAllocator with another allocator and calls deinit on the arena when the book is torn down. section 5.3.2

Listing 5.4 Giving the recipe book blank pages to fill
const std = @import("std");
const Allocator = std.mem.Allocator;

const RecipeId = enum (c_int) { _ };

const RecipeBook = struct {
    const Recipe = struct {
        name: [:0]const u8,
        author: [:0]const u8,
        instructions: [:0]const u8,
    };

    const Ingredient = struct {
        recipe_id: RecipeId,
        quantity: [:0]const u8,
        name: [:0]const u8,
    };

    string_arena: std.heap.ArenaAllocator,
    recipes: std.AutoHashMapUnmanaged(RecipeId, Recipe),
    ingredients: std.ArrayList(Ingredient),

    fn init(ally: Allocator) RecipeBook { #1
        return .{
            .string_arena = .init(ally),
            .recipes = .empty,
            .ingredients = .empty,
        };
    }

    fn deinit(self: *RecipeBook, ally: Allocator) void { #2
        self.string_arena.deinit(); #3
        self.recipes.deinit(ally); #3
        self.ingredients.deinit(ally); #3
    }
};

See how the recipe book keeps its string arena alongside its recipe map and ingredient list. section 5.3.2

Choose an arena when allocations naturally finish their work together. It is a poor fit when you need to reclaim each allocation as you go: keeping a group alive also keeps its storage around until cleanup. For a file-printing loop, a general-purpose allocator and defer let each file's contents be freed after use, even if writing fails. section 3.4.2

One-shot JSON parsing

Loading a recipe book uses a temporary arena for JSON parsing. The arena supplies an allocator to std.json.Reader and std.json.parseFromTokenSourceLeaky, and defer releases it when the function exits. Strings copied into the resulting recipe book must outlive that temporary parsing arena. section 5.3.4

Listing 5.13 Book from json
fn fromJson(ally: Allocator, reader: *std.Io.Reader) !RecipeBook {
    var arena: std.heap.ArenaAllocator = .init(ally); #1
    defer arena.deinit();
    const arena_ally = arena.allocator(); #1

    var json_reader = std.json.Reader.init(arena_ally, reader); #2
    const repr = try std.json.parseFromTokenSourceLeaky( #3
        JsonRepr,
        arena_ally,
        &json_reader,
        .{},
    );

    var self: RecipeBook = .init(ally); #4
    for (repr.recipes) |pair| {
        try self.recipes.put(ally, pair.recipe_id, .{ #5
            .name = try self.dupeCString(pair.recipe.name),
            .author = try self.dupeCString(pair.recipe.author),
            .instructions = try self.dupeCString(pair.recipe.instructions),
        });
    }
    for (repr.ingredients) |ingredient| { #6
        try self.ingredients.append(ally, .{
            .recipe_id = ingredient.recipe_id,
            .quantity = try self.dupeCString(ingredient.quantity),
            .name = try self.dupeCString(ingredient.name),
        });
    }
    self.next_recipe_num = repr.next_recipe_num;

    return self;
}

Follow the temporary arena from initialization through parsing and copying recipe strings. section 5.3.4

How Systems Programming with Zig covers it

How deep it goes
Explains initialization, allocator access, cleanup, and lifetime trade-offs without detailing arena internals.
Examples
Uses a recipe book's strings, a JSON loading function, and a file-printing loop to illustrate allocation choices.
What you can do after
Apply it via Zig's std.heap.ArenaAllocator to group allocations and release them at the end of a shared lifetime.
How it connects
Connects arena allocation to manual memory management, general-purpose allocators, JSON parsing, and string lifetimes.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Systems Programming with Zig. The section links point to the parts of the book it draws on.