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
DebugAllocatortracks every allocation; itsdeinitreports leaks at exit.alloc.alloc(u8, 24)rents a slice;defer alloc.free(line)returns it.@memsetfills the rented bytes before they print.
Keywords and builtins used here
constdeferfnpubtryu8varvoid
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.
Step 1 of 3 in Memory, step 19 of 27 in Language basics.