Zig Allocators
In Zig Memory Basics you saw that heap memory comes from an allocator. This lesson is about that allocator: what it actually is, and the handful of calls you’ll use every day. The good news is that every allocator in Zig, fast or slow, simple or clever, is used in exactly the same way. Learn the calls once and they work everywhere.
An allocator is a value you pass around
Section titled “An allocator is a value you pass around”In C there’s one global malloc. In Zig, an allocator is an ordinary value of type std.mem.Allocator. You get one, keep it in a variable, and hand it to the functions that need memory:
const std = @import("std");
fn makeZeros(allocator: std.mem.Allocator, n: usize) ![]u32 { const nums = try allocator.alloc(u32, n); @memset(nums, 0); return nums;}
pub fn main(init: std.process.Init) !void { const gpa = init.gpa;
const zeros = try makeZeros(gpa, 3); defer gpa.free(zeros);
std.debug.print("{any}\n", .{zeros});}Output:
{ 0, 0, 0 }init.gpa is the general-purpose allocator main gets for free (gpa stands for “general purpose allocator”). makeZeros doesn’t know or care which allocator it was given. It just calls alloc on whatever came in. That’s the whole idea: the function says “I need memory”, and the caller decides where it comes from. The next lesson, Zig Choosing an Allocator, is about which one to pick.
alloc and free: many items
Section titled “alloc and free: many items”allocator.alloc(T, n) asks for room for n values of type T and gives back a slice, []T. allocator.free(slice) gives it back. Always in pairs:
const std = @import("std");
pub fn main(init: std.process.Init) !void { const gpa = init.gpa;
const scores = try gpa.alloc(u8, 4); defer gpa.free(scores);
std.debug.print("fresh: {any}\n", .{scores});
@memset(scores, 0); scores[1] = 42; std.debug.print("after: {any}\n", .{scores});}Output:
fresh: { 170, 170, 170, 170 }after: { 0, 42, 0, 0 }Look at the first line. New memory is not zeroed. Its contents are undefined, and in debug builds (the default) Zig fills undefined bytes with 0xaa (170) on purpose, so you notice when you read something you never set. In a fast build it could be anything. So always fill new memory before you read it: @memset, a loop, or @memcpy.
Why try? Asking for memory can fail, for example when the computer is out of it. Then alloc returns error.OutOfMemory instead of a slice, and try passes that error up to the caller. That’s why main returns !void. You’ll learn errors properly in Zig Errors.
create and destroy: one value
Section titled “create and destroy: one value”For a single value, like one struct, use allocator.create(T). It gives back a pointer, *T, and allocator.destroy(ptr) gives it back:
const std = @import("std");
const Player = struct { name: []const u8, score: u32,};
pub fn main(init: std.process.Init) !void { const gpa = init.gpa;
const p = try gpa.create(Player); defer gpa.destroy(p);
p.* = .{ .name = "Ana", .score = 0 }; p.score += 10; std.debug.print("{s} has {d} points\n", .{ p.name, p.score });}Output:
Ana has 10 pointsLike alloc, create gives you undefined memory, so fill it in before you use it. p.* = .{ ... } writes a whole Player into it at once.
When would you put one struct on the heap instead of in a local variable? When it has to outlive the function that made it, or when lots of other things will hold a pointer to it, like a node in a linked list or a tree.
Don’t mix them up
Section titled “Don’t mix them up”The pairs are strict: alloc goes with free, create goes with destroy. Zig checks this while compiling. Here’s destroy given a slice:
const std = @import("std");
pub fn main(init: std.process.Init) !void { const gpa = init.gpa; const nums = try gpa.alloc(u32, 3); gpa.destroy(nums);}lib/std/mem/Allocator.zig:203:28: error: ptr must be a single item pointer if (info.size != .one) @compileError("ptr must be a single item pointer"); ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~referenced by: main: main.zig:6:16The error points into the standard library, which looks scary, but read the referenced by: line: main.zig:6:16 is your call. Going the other way, free on a pointer from create, gives a much less helpful message, error: reached unreachable code, again with your line under referenced by:. If you see either one near an allocator call, check you’ve got the right pair.
Handy helpers: dupe and print
Section titled “Handy helpers: dupe and print”Two calls you’ll use all the time are built on top of alloc:
allocator.dupe(T, slice)makes a copy of a slice in new memory.allocator.print(format, args)builds a formatted string in new memory, likestd.debug.printbut into a string.
const std = @import("std");
pub fn main(init: std.process.Init) !void { const gpa = init.gpa;
var buf = [_]u8{ 'z', 'i', 'g' }; const copy = try gpa.dupe(u8, &buf); defer gpa.free(copy); buf[0] = 'Z';
const line = try gpa.print("{s} has {d} letters", .{ copy, copy.len }); defer gpa.free(line);
std.debug.print("buf: {s}\n", .{&buf}); std.debug.print("{s}\n", .{line});}Output:
buf: Zigzig has 3 lettersChanging buf after the copy doesn’t touch copy: it has its own bytes. Both results came from the allocator, so both need a free. (If you’ve seen std.fmt.allocPrint in older code, it’s the same thing. In 0.17 it moved to allocator.print, as the 0.17.0 release notes explain.)
Growing and shrinking: realloc and resize
Section titled “Growing and shrinking: realloc and resize”Sometimes you need more room than you first asked for. allocator.realloc(slice, new_len) gives you a slice of the new length, keeping the old items:
const std = @import("std");
pub fn main(init: std.process.Init) !void { const gpa = init.gpa;
var nums = try gpa.alloc(u32, 2); defer gpa.free(nums); nums[0] = 1; nums[1] = 2;
nums = try gpa.realloc(nums, 4); nums[2] = 3; nums[3] = 4;
std.debug.print("{any}\n", .{nums});}Output:
{ 1, 2, 3, 4 }Two things to notice:
reallocmay move the items to a new place. The old slice is no longer valid, which is why we store the result back innums(that’s also whynumsis avar).- The
defer gpa.free(nums)was written before therealloc, and it still frees the right memory. Adeferreadsnumswhen it runs, at the end, so it sees the new slice.
There’s also allocator.resize(slice, new_len), which tries to change the size without moving. It returns a bool, and it’s allowed to say no:
const std = @import("std");
pub fn main(init: std.process.Init) !void { const gpa = init.gpa;
var nums = try gpa.alloc(u32, 4); defer gpa.free(nums); @memset(nums, 7);
if (gpa.resize(nums, 3)) { nums = nums[0..3]; std.debug.print("shrunk in place\n", .{}); } else { std.debug.print("resize said no, still {d} items\n", .{nums.len}); }}Output:
resize said no, still 4 itemsIn a debug build, init.gpa said no even to shrinking. Other allocators might say yes. That’s the point: resize is a “try it cheaply” call, and your code must work either way. In practice you’ll rarely call realloc or resize yourself, because Zig ArrayList does the growing for you.
Writing your own functions that allocate
Section titled “Writing your own functions that allocate”When you write a function that needs heap memory, follow the same shape as the standard library:
- Take a
std.mem.Allocatoras a parameter (usually the first one). - Return an error union like
![]u8, because allocating can fail. - Say in a doc comment that the caller owns the result and must free it.
const std = @import("std");
/// Returns `text` repeated `times` times./// Caller owns the returned memory.fn repeat(allocator: std.mem.Allocator, text: []const u8, times: usize) ![]u8 { const out = try allocator.alloc(u8, text.len * times); for (0..times) |i| { @memcpy(out[i * text.len ..][0..text.len], text); } return out;}
pub fn main(init: std.process.Init) !void { const gpa = init.gpa;
const cheer = try repeat(gpa, "hip ", 3); defer gpa.free(cheer);
std.debug.print("{s}hooray!\n", .{cheer});}Output:
hip hip hip hooray!repeat allocates and returns; main frees. “Caller owns the returned memory” is a phrase you’ll see all over the standard library’s doc comments, and it’s the most common rule for who frees what. Zig Lifetimes & Ownership covers the others.
out[i * text.len ..][0..text.len] reads as “start at i * text.len, then take text.len items”. It’s a common Zig way to say “a piece of this length, starting here”.
Practice
Section titled “Practice”1. Copy and shout
Section titled “1. Copy and shout”Write a program that copies the text "hello" into new memory with dupe, changes every letter in the copy to upper case with std.ascii.toUpper, and prints both the original and the copy.
Hint: loop with for (copy) |*c| c.* = std.ascii.toUpper(c.*);, and don’t forget defer gpa.free(copy);.
Show solution
const std = @import("std");
pub fn main(init: std.process.Init) !void { const gpa = init.gpa;
const original = "hello"; const copy = try gpa.dupe(u8, original); defer gpa.free(copy);
for (copy) |*c| c.* = std.ascii.toUpper(c.*); std.debug.print("{s} {s}\n", .{ original, copy });}Output:
hello HELLOA string literal is read-only, so you can’t change original. dupe gives you a copy you own, and can change.
2. A counter on the heap
Section titled “2. A counter on the heap”Make a struct Counter with one field count: u32. Put one on the heap with create, add 1 to it three times, print the count and give it back with destroy.
Hint: after create, set it with c.* = .{ .count = 0 }; before you use it.
Show solution
const std = @import("std");
const Counter = struct { count: u32,};
pub fn main(init: std.process.Init) !void { const gpa = init.gpa;
const c = try gpa.create(Counter); defer gpa.destroy(c); c.* = .{ .count = 0 };
for (0..3) |_| c.count += 1; std.debug.print("count: {d}\n", .{c.count});}Output:
count: 3create and destroy are the single-value pair. Through the pointer c, you can still write c.count, and Zig follows the pointer for you.
3. A label maker
Section titled “3. A label maker”Write a function label(allocator, name, number) that returns a new string like "box-7" built with allocator.print. Call it twice from main, print both labels and free both.
Hint: the return type is ![]u8, and the body is one line: return allocator.print("{s}-{d}", .{ name, number });.
Show solution
const std = @import("std");
/// Caller owns the returned memory.fn label(allocator: std.mem.Allocator, name: []const u8, number: u32) ![]u8 { return allocator.print("{s}-{d}", .{ name, number });}
pub fn main(init: std.process.Init) !void { const gpa = init.gpa;
const a = try label(gpa, "box", 7); defer gpa.free(a); const b = try label(gpa, "shelf", 12); defer gpa.free(b);
std.debug.print("{s} {s}\n", .{ a, b });}Output:
box-7 shelf-12Each call makes its own string, so each gets its own defer free. The doc comment tells whoever calls label that freeing is their job.
- An allocator is a value of type
std.mem.Allocatorthat you pass to whatever needs memory. alloc(T, n)gives a slice and pairs withfree;create(T)gives a pointer and pairs withdestroy.- New memory is undefined (
0xaabytes in debug builds). Fill it before you read it. - Allocating can fail with
error.OutOfMemory, so the calls needtry. dupecopies a slice,printbuilds a formatted string,reallocgrows or shrinks (and may move).- Functions that allocate take an allocator and usually say “caller owns the returned memory”.
Next up: Zig Choosing an Allocator, the allocators in the standard library and when to use each.
Quick check
Section titled “Quick check”Quick check
Read more
Section titled “Read more”- Zig language reference: Memory: why functions that allocate take an
Allocatorparameter. - std.mem.Allocator source (0.17.1): short and readable, with a doc comment on every call in this lesson.
- Zig 0.17.0 release notes: what changed for allocators, including
allocator.print. - Learning Zig: Heap Memory & Allocators: a friendly community guide. Written for an older Zig, so some names differ.