Looking for a structured path? Browse all Zig lessons.

Maintained by
Learning Platform content team
Reviewed by
Learning Platform source and executable-example contract

Zig 0.16 allocator patterns: ownership and cleanup

Zig makes allocation a visible dependency. Code that needs dynamic memory usually accepts a std.mem.Allocator; the caller chooses the policy and owns the corresponding cleanup.

Caller-provided allocator

const std = @import("std");

fn doubled(allocator: std.mem.Allocator, input: []const u8) ![]u8 {
    const output = try allocator.alloc(u8, input.len * 2);
    @memcpy(output[0..input.len], input);
    @memcpy(output[input.len..], input);
    return output;
}

pub fn main() !void {
    const allocator = std.heap.page_allocator;
    const output = try doubled(allocator, "zig");
    defer allocator.free(output);
    std.debug.print("{s}\n", .{output});
}

Expected output: zigzig. The return type []u8 communicates that a new buffer exists, but prose/API documentation must still say that the caller frees it with the same allocator.

Pick lifetime policy at the application boundary

  • Use a general-purpose allocator when you want leak/double-free diagnostics during development.
  • Use an arena when many allocations share one lifetime; call deinit once for the whole arena.
  • Use the page allocator for simple examples and coarse allocations, not as an automatic production default.
  • Use fixed buffers when bounded memory and allocation failure behavior must be explicit.

Allocator setup APIs have changed across Zig releases. Keep the project toolchain pinned and consult its standard-library source instead of copying an older blog's initialization syntax.

defer and errdefer

Use defer after successful acquisition for normal cleanup. Use errdefer when a partially built value must be released only if the function exits with an error.

Failure modes

Returning a slice backed by a local stack array creates a dangling reference. Freeing with a different allocator is invalid. An arena does not make memory free: it postpones reclamation until arena teardown, so an unbounded long-lived arena still grows.

Continue in Memory and Allocators, review Pointers, and try small snippets in the Zig playground.

Official references