typestar

Allocators in Zig

Nothing allocates behind your back: rent bytes from an allocator, free them, get audited.

const std = @import("std");

pub fn main() !void {
    // Nothing allocates without being handed an allocator.
    var gpa = std.heap.DebugAllocator(.{}){};
    defer _ = gpa.deinit(); // reports leaks at exit
    const alloc = gpa.allocator();

    const line = try alloc.alloc(u8, 24);
    defer alloc.free(line);

    @memset(line, '~');
    std.debug.print("{s}\n", .{line});
    std.debug.print("rented {d} bytes, returned on exit\n", .{line.len});
}

How it works

  1. DebugAllocator tracks every allocation; its deinit reports leaks at exit.
  2. alloc.alloc(u8, 24) rents a slice; defer alloc.free(line) returns it.
  3. @memset fills the rented bytes before they print.

Keywords and builtins used here

The run, in numbers

Lines
15
Characters to type
419
Tokens
119
Three-star pace
65 tpm

At the three-star pace of 65 tokens a minute, this run takes about 110 seconds.

Type this snippet

Step 1 of 3 in Memory, step 19 of 27 in Language basics.

← Previous Next →