Explicit memory management means program code controls the allocation, ownership, and release of dynamically used memory. In Zig, allocator choices make that control configurable, while pointer types and safety checks help make unsafe memory operations harder to perform. section 1.2.3
Start by asking how long each piece of data needs to live. An arena allocator can give many allocations the same lifetime and release them together. Choosing allocators around those lifetimes can keep memory bookkeeping out of the way without surrendering control. section 5.3.2
A recipe book with shared string lifetimes
A RecipeBook stores recipe and ingredient strings in an arena so they can live as long as the book. Its representation also holds recipes in a hash map and ingredients in an array list. Initialization receives an allocator for the arena; deinitialization releases the arena. 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
}
};
Inspect the RecipeBook fields and initialization to see how the arena sits alongside the collections. section 5.3.2
Allocators are building blocks: they can be swapped, stacked, configured, or implemented for a particular need. The payoff is an abstraction over memory bookkeeping that still leaves the programmer in control. section 5.3.2

