Designing Zig Libraries Around Explicit Allocators
Zig requires callers to pass an allocator. This guide covers API design, trust boundaries, failure modes, and operational checks for explicit memory management.
13 Sept 2026, 17:48 UTC

The problem: hidden allocation and unclear ownership
In many languages, a library can allocate memory behind the caller's back through a global heap. The caller receives a value and may not know who owns it, how long it lives, or what happens when memory runs out. Zig removes that ambiguity: standard library components that allocate require an allocator argument, commonly std.mem.Allocator in recent pre-1.0 releases. The caller supplies the allocation policy, and every allocation site returns an error union instead of assuming success.
Useful takeaway: design Zig APIs so the caller passes the allocator, treat every allocation as fallible, and make memory lifetime visible at the trust boundary.
Requirements
- Data structures must not allocate without caller consent.
- Allocation failures must be representable and propagatable.
- Memory ownership and lifetime must be auditable at API boundaries.
- Test-only allocators must not leak into production builds.
Smallest suitable design
The smallest design is a function or type that accepts std.mem.Allocator and uses it for every internal allocation. For example, a helper that splits input into owned strings:
const std = @import("std");
pub fn splitOwned(allocator: std.mem.Allocator, input: []const u8, separator: u8) ![]const u8 {
var list = std.ArrayList(u8).init(allocator);
defer list.deinit();
var start: usize = 0;
while (start < input.len) : (start += 1) {
const end = std.mem.indexOf(u8, input[start..], separator) orelse input.len;
try list.append(input[start..start + end]);
if (end == input.len) break;
start += end;
}
return list.toOwnedSlice();
}
ArrayList.init requires the allocator. try list.append propagates error.OutOfMemory instead of crashing silently. defer list.deinit makes lifetime explicit: the caller owns the returned slice and must free it with the same allocator.
Allocator choice by context
| Allocator | Best for | Trade-off |
|---|---|---|
std.heap.FixedBufferAllocator | Embedded or bounded memory | Fixed capacity; returns error.OutOfMemory when full |
std.heap.GeneralPurposeAllocator | General production use | Heap-backed; tracks leaks in debug mode |
std.heap.ArenaAllocator | Short-lived batches | Frees all memory at once on deinit; no individual frees |
std.testing.allocator | Tests only | Does not free memory; unsuitable for production accounting |
Trust and data boundaries
Because a library cannot allocate behind the caller's back, the trust boundary is the allocator parameter itself. The caller decides which memory pool backs the data, and the library must not retain the allocator beyond the call unless it documents ownership. A function that returns allocated memory transfers responsibility to the caller; the caller must free it with a compatible allocator.
A common boundary error is passing std.testing.allocator into production code. It deliberately does not release allocations so leaks are easier to catch under debug tooling, but it hides memory pressure and leaks in production. Reserve it for test builds.
Operational checks
Run these checks in a terminal with no special permissions required.
- Identify the toolchain:
zig version. The output tells you whether the standard library exposesstd.mem.Allocatoror the olderstd.heap.Allocator; examples are version-sensitive. - Compile a minimal program:
zig build-exe <source.zig>. Constructstd.ArrayList(u8).init(allocator). Omitting the allocator argument should be a compile-time error. - Inject failure: wrap a
FixedBufferAllocatorsized too small for the workload and confirm call sites usingtrypropagateerror.OutOfMemoryrather than succeeding silently. - Inspect standard library source for fallible helpers such as file-reading allocation functions. Verify the signature includes an allocator parameter and returns an error union.
Risk: copying an example from one Zig release to another can fail to compile because the allocator interface name changed between releases. Verify against your installed standard library before adopting code.
Failure modes
- Unhandled out-of-memory. Using
trypropagates the error; usingcatch unreachablecrashes under memory pressure instead of degrading gracefully. - Thread sharing. Standard allocators are generally not thread-safe. Sharing one instance across threads requires external synchronization or per-thread allocator instances.
- Test allocator in production.
std.testing.allocatornever frees, so long-running production use exhausts memory without reporting it. - Mismatched allocator lifetime. Freeing memory with a different allocator than the one that allocated it is undefined behavior.
Conditions that would change the design
- If the target is embedded with a fixed RAM budget, replace
GeneralPurposeAllocatorwithFixedBufferAllocatorand size the buffer at compile time. - If the library serves concurrent requests, avoid a shared allocator; pass per-request or per-thread allocators, or serialize access with a mutex.
- If allocations are short-lived and numerous, an
ArenaAllocatorreduces per-allocation overhead, but you lose the ability to free individual items.
Limitations
Zig is pre-1.0, so the allocator interface and standard library signatures can change between releases. This article assumes a recent pre-1.0 toolchain where std.mem.Allocator is used. There is no global heap to fall back to, which means more explicit boilerplate at every call site.
Practical verification
After integrating an allocator parameter, build with zig build-exe -O Debug <source.zig> and run under a memory leak detector if available. Then reproduce memory pressure with a small FixedBufferAllocator and confirm every allocation site either handles error.OutOfMemory or fails safely. If the program compiles and allocation failures surface as error unions rather than crashes, the boundary is working as intended.
0 replies
A thoughtful contribution can make all the difference. Be the first to share one.