Skip to content

Zig Arena Allocator

Freeing every allocation one by one gets tiring, and it’s easy to miss one. Often you don’t need to: a lot of memory is only needed until some moment, like the end of the program, the end of one web request, or the end of one game frame, and then all of it can go together. That’s what an arena is for. You allocate as much as you like, never call free, and give it all back in one go. It’s one of the most useful tools in Zig, and it makes manual memory feel a lot less manual.

Picture a notepad. You write on page after page, and you never erase single lines. When you’re done with the job, you tear off all the used pages at once and throw them away. That’s an arena.

A general-purpose allocator is more like a filing cabinet: each folder goes back in its own slot, one at a time. More work, but you can keep some folders and return others.

Here’s an arena in action:

const std = @import("std");
pub fn main(init: std.process.Init) !void {
var arena: std.heap.ArenaAllocator = .init(init.gpa);
defer arena.deinit();
const a = arena.allocator();
const sentence = "the quick brown fox";
var words: std.ArrayList([]const u8) = .empty;
var it = std.mem.tokenizeScalar(u8, sentence, ' ');
while (it.next()) |word| {
const loud = try a.dupe(u8, word);
for (loud) |*c| c.* = std.ascii.toUpper(c.*);
try words.append(a, loud);
}
std.debug.print("{d} words\n", .{words.items.len});
for (words.items) |w| std.debug.print("{s}\n", .{w});
}

Output:

4 words
THE
QUICK
BROWN
FOX

Count the allocations: one dupe per word, plus whatever the ArrayList needs as it grows. Count the frees: zero. There’s no defer gpa.free(loud), and no words.deinit(...). The single defer arena.deinit(); at the top gives back every byte when main ends.

The setup is the shape you saw in Zig Choosing an Allocator:

  1. var arena: std.heap.ArenaAllocator = .init(init.gpa); makes the arena. It needs a backing allocator (here init.gpa) to get its big chunks of memory from.
  2. arena.allocator() gives you the std.mem.Allocator to pass around.
  3. arena.deinit() frees everything.

init.arena: an arena for the whole program

Section titled “init.arena: an arena for the whole program”

main gets an arena of its own: init.arena. It lives until the program exits, and Zig cleans it up for you, so you don’t even write a deinit:

const std = @import("std");
fn configLine(a: std.mem.Allocator, key: []const u8, value: u32) ![]const u8 {
return a.print("{s}={d}", .{ key, value });
}
pub fn main(init: std.process.Init) !void {
const arena = init.arena.allocator();
const width = try configLine(arena, "width", 800);
const height = try configLine(arena, "height", 600);
std.debug.print("{s}\n{s}\n", .{ width, height });
}

Output:

width=800
height=600

Note that init.arena is a pointer to an ArenaAllocator, not an allocator itself, so you call .allocator() on it. Use it for things that really do live as long as the program: the command-line arguments, a config file you read at the start, a lookup table you build once. Zig CLI Arguments uses it for exactly that.

Programs that work in rounds, like a server answering requests or a game drawing frames, are where arenas really earn their place. Make one arena, use it for everything in one round, then reset it before the next round:

const std = @import("std");
pub fn main(init: std.process.Init) !void {
var arena: std.heap.ArenaAllocator = .init(init.gpa);
defer arena.deinit();
const a = arena.allocator();
const requests = [_][]const u8{ "/home", "/about", "/blog" };
for (requests, 1..) |path, n| {
defer _ = arena.reset(.retain_capacity);
const page = try a.print("<h1>{s}</h1>", .{path[1..]});
const log = try a.print("request {d}: {s} ({d} bytes)", .{ n, path, page.len });
std.debug.print("{s}\n", .{log});
}
}

Output:

request 1: /home (13 bytes)
request 2: /about (14 bytes)
request 3: /blog (13 bytes)

Each round makes two strings and frees neither. The defer at the top of the loop body resets the arena at the end of each round, so the strings from round 1 are gone before round 2 starts. Without the reset, the arena would keep growing for as long as requests keep coming.

reset takes a mode:

  • .retain_capacity throws away everything but keeps the memory chunks, so the next round can reuse them without asking the backing allocator again. Good for loops.
  • .free_all gives all the memory back, like deinit, but the arena can still be used.
  • .{ .retain_with_limit = n } keeps up to n bytes and frees the rest, for when one huge round shouldn’t hold on to memory forever.

reset returns a bool (whether keeping the capacity worked; the arena is fine either way), so we discard it with _ =.

The one big mistake: memory that outlives its arena

Section titled “The one big mistake: memory that outlives its arena”

Everything from an arena dies with the arena. So never let a slice from an arena escape past its deinit or reset. Here’s the classic version, a function with its own arena that returns a string from it:

const std = @import("std");
fn makeTitle(gpa: std.mem.Allocator, name: []const u8) ![]const u8 {
var arena: std.heap.ArenaAllocator = .init(gpa);
defer arena.deinit();
return arena.allocator().print("Dr. {s}", .{name});
}
pub fn main(init: std.process.Init) !void {
const title = try makeTitle(init.gpa, "Ana");
std.debug.print("{s}\n", .{title});
}

When we ran this in a debug build, it printed:

UUUUUUU

The defer arena.deinit() ran as makeTitle returned, so title points at memory that’s already been given back. In debug builds, freed memory gets filled with the byte 0x55, which happens to be the letter U, so the bug shows up as a row of U’s. In a fast build the same program printed Dr. Ana when we tried it, which is worse: the bug is still there, just hidden.

The fix is to let the caller decide where the string lives. Take the allocator as a parameter and allocate from it directly:

const std = @import("std");
fn makeTitle(a: std.mem.Allocator, name: []const u8) ![]const u8 {
return a.print("Dr. {s}", .{name});
}
pub fn main(init: std.process.Init) !void {
const title = try makeTitle(init.arena.allocator(), "Ana");
std.debug.print("{s}\n", .{title});
}

Output:

Dr. Ana

Now the string lives in init.arena, which lasts until the program ends. This is the same “caller decides” rule from Zig Allocators, and Zig Lifetimes & Ownership goes deeper into it.

Arenas are great until memory needs to be freed at different times. A few signs you want a general-purpose allocator instead:

  • A long-running program that keeps adding and removing things, like a cache. Removed items never really go away in an arena, so memory only grows until the next reset.
  • One list that grows a lot. When an ArrayList grows, it moves its items to a bigger buffer and frees the old one. In an arena, that “free” usually does nothing, so the old buffers stay until reset.
  • Data that must outlive the round. If one result from a request has to be kept, copy it out to a longer-lived allocator before you reset.

Since Zig 0.16 the arena is also safe to use from several threads at once, as the 0.16.0 release notes explain, so sharing one between threads is fine.

Rewrite this program to use an arena on top of init.gpa, so there’s only one cleanup line instead of three.

const std = @import("std");
pub fn main(init: std.process.Init) !void {
const gpa = init.gpa;
const a = try gpa.dupe(u8, "red");
defer gpa.free(a);
const b = try gpa.dupe(u8, "green");
defer gpa.free(b);
const c = try gpa.print("{s} and {s}", .{ a, b });
defer gpa.free(c);
std.debug.print("{s}\n", .{c});
}

Hint: make the arena, defer arena.deinit();, then use arena.allocator() for all three calls.

Show solution
const std = @import("std");
pub fn main(init: std.process.Init) !void {
var arena: std.heap.ArenaAllocator = .init(init.gpa);
defer arena.deinit();
const al = arena.allocator();
const a = try al.dupe(u8, "red");
const b = try al.dupe(u8, "green");
const c = try al.print("{s} and {s}", .{ a, b });
std.debug.print("{s}\n", .{c});
}

Output:

red and green

All three strings die together at arena.deinit(). We named the allocator al because a was already taken by the first string.

Write a loop over frames 1 to 3. In each frame, use an arena to build the text "frame N" with print and print it. Reset the arena at the end of each frame with .retain_capacity.

Hint: for (1..4) |n| { defer _ = arena.reset(.retain_capacity); ... }.

Show solution
const std = @import("std");
pub fn main(init: std.process.Init) !void {
var arena: std.heap.ArenaAllocator = .init(init.gpa);
defer arena.deinit();
const a = arena.allocator();
for (1..4) |n| {
defer _ = arena.reset(.retain_capacity);
const text = try a.print("frame {d}", .{n});
std.debug.print("{s}\n", .{text});
}
}

Output:

frame 1
frame 2
frame 3

Each frame’s text is thrown away when the frame ends, but the arena keeps its chunk of memory, so frames 2 and 3 don’t need to ask init.gpa for anything new.

  • An arena hands out memory and frees everything at once with deinit.
  • Set it up with var arena: std.heap.ArenaAllocator = .init(backing);, then arena.allocator().
  • free on an arena usually does nothing, so code that frees still works with it.
  • init.arena lasts the whole program, with no deinit to write. Call init.arena.allocator().
  • In loops, arena.reset(.retain_capacity) clears a round’s memory and reuses it.
  • Never let arena memory outlive the arena: take the allocator as a parameter instead.

Next up: Zig Memory Leaks, what a leak looks like and how Zig points you straight at it.

Quick check

1. You allocate 50 strings from an arena and free none of them. When is the memory given back?
2. How do you get an allocator from init.arena?
3. A function makes its own arena, defers arena.deinit(), and returns a string allocated from it. What is wrong?
4. Which job is an arena a poor fit for?