Skip to content
Tutorials Center
My learning

Topics

Lesson 21 of 37 ยท Allocators and Error Handling

Allocating and Freeing Memory

Allocate slices and single items in Zig with alloc, create, dupe and realloc, free them with defer, and avoid leaks and use-after-free, with examples and a Go stand-in.

Once you have an allocator (see Allocators in Zig), four everyday functions do most of the work: alloc and free for slices, create and destroy for single values. They always come in pairs. A good habit is to write the defer that frees a value on the line right after you allocate it, so you cannot forget.

Slices with alloc and free

allocator.alloc(T, n) returns a ![]T: a slice of n items, or error.OutOfMemory. The memory is uninitialized, so fill it before reading.

ZIG
const std = @import("std");

pub fn main() !void {
    const gpa = std.heap.page_allocator;

    const squares = try gpa.alloc(u32, 5);
    defer gpa.free(squares);

    for (squares, 0..) |*slot, i| {
        slot.* = @intCast(i * i);
    }
    std.debug.print("{any}\n", .{squares}); // { 0, 1, 4, 9, 16 }
}

free takes the slice itself, so the allocator knows the length. If you want a zero-filled slice, call alloc and then @memset(slice, 0).

Single items with create and destroy

allocator.create(T) returns !*T, a pointer to one uninitialized value. Pair it with destroy.

ZIG
const Point = struct { x: f32, y: f32 };

const p = try gpa.create(Point);
defer gpa.destroy(p);
p.* = .{ .x = 1.5, .y = -2 };

Heap-allocating a lone struct is less common in Zig than in Java or C++: small structs live happily on the stack or inside a larger slice. You reach for create for things whose address must stay stable, such as nodes of a linked list or tree.

Copying with dupe

dupe allocates a copy of a slice. It is the standard way to take ownership of a string you were only borrowing:

ZIG
const name: []const u8 = "ziggy";
const owned = try gpa.dupe(u8, name);
defer gpa.free(owned);

allocPrint does the same but formats text, and dupeZ appends a zero terminator for C APIs (see Calling C from Zig).

Resizing with realloc

realloc(old_slice, new_len) returns a new slice, possibly at a different address. Use the returned value and forget the old one:

ZIG
var items = try gpa.alloc(u8, 4);
items = try gpa.realloc(items, 8);
defer gpa.free(items);

In practice you rarely call realloc yourself: std.ArrayList does it for you (next lesson).

defer, errdefer and ownership

defer runs when the scope ends, in reverse order of declaration. That pairs nicely with allocation:

ZIG
fn load(gpa: std.mem.Allocator) !void {
    const a = try gpa.alloc(u8, 100);
    defer gpa.free(a);
    const b = try gpa.alloc(u8, 200);
    defer gpa.free(b);
    // if anything below returns an error, both a and b are freed
}

When a function returns the memory to its caller, a plain defer free would free it too early. That is what errdefer is for: it runs only when the function exits with an error. See errdefer and error sets.

ZIG
fn makeBuffer(gpa: std.mem.Allocator, n: usize) ![]u8 {
    const buf = try gpa.alloc(u8, n);
    errdefer gpa.free(buf); // free only if later code fails
    try fill(buf);          // may return an error
    return buf;             // caller now owns buf
}

A useful convention: document who owns what. If a function returns allocated memory, the doc comment says "caller owns the returned slice".

Ownership diagram

sequenceDiagram
  participant C as caller
  participant F as makeBuffer
  participant A as allocator
  C->>F: makeBuffer(gpa, 64)
  F->>A: alloc(u8, 64)
  A-->>F: slice
  F-->>C: return slice (caller owns it)
  C->>A: free(slice) via defer

Caption: the function creates the slice, then the caller becomes the owner and frees it.

Bugs the tools catch

  • Leak: DebugAllocator.deinit() returns .leak and prints where the memory came from.
  • Double free and use-after-free: the debug allocator detects both and reports a stack trace instead of silently corrupting memory.
  • Wrong allocator on free: undefined behavior in release builds, so keep one allocator per ownership chain.
  • Reading uninitialized memory: fresh alloc results hold garbage. Debug builds fill it with 0xaa so bugs show up quickly.

A runnable stand-in

Go frees memory for you, but we can mimic Zig's pairing discipline with an explicit "allocator" that counts live bytes and uses defer to free. This is a Go stand-in for the idea, not Zig.

Go Stand-in: counting allocator with defer in Go

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Zig's DebugAllocator does the same bookkeeping for real, and reports the leak with a stack trace when you call deinit.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which pair allocates and frees a slice?

    alloc returns a slice and free takes that slice. create/destroy are for a single item.
  2. 2. What does a fresh result of allocator.alloc contain?

    alloc does not initialize. Fill the slice (for example with @memset) before reading it.
  3. 3. Why use errdefer for memory you plan to return?

    A plain defer would free the buffer even on success. errdefer runs only on the error path.
  4. 4. What does dupe do?

    dupe allocates new memory and copies the contents, giving you an owned copy.

Summary

  • alloc/free handle slices; create/destroy handle single items; dupe copies; realloc resizes.
  • Put the defer free directly after the allocation.
  • Use errdefer when ownership moves to the caller on success.
  • The debug allocator finds leaks, double frees and use-after-free.

Next: ArrayList and hash maps