Back to course

Memory Allocation and Allocators

Full Course: Zig Programming From Zero to Hero

Memory Management in Zig

Zig does not have a global allocator by default. You must pass an Allocator to functions that need to allocate memory. This is called Explicit Resource Management.

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

pub fn main() !void { var gpa = std.heap.GeneralPurposeAllocator(.{}){}; const allocator = gpa.allocator();

const bytes = try allocator.alloc(u8, 100);
defer allocator.free(bytes);

}

This makes it very clear where and how memory is allocated.