Skip to content

Zig Memory Basics

If you come from Python, JavaScript or Go, you’ve probably never had to think about where your data lives. You make a list, add things to it, and a garbage collector cleans up when you’re done. Zig has no garbage collector. Every byte your program uses lives in one of a few places, and you decide which. That sounds like a lot of work, but there are only three places, and once you can picture them, the rest of this section (allocators, arenas, leaks, ownership) falls into place. This lesson is the picture.

The Zig reference has a section with exactly that title, and it’s the question to keep asking. Every value in your program sits in one of three places:

  • Global data: string literals like "hello", and const and var declared at the top of a file. They exist for the whole run of the program.
  • The stack: the local variables of a function. They appear when the function is called and disappear when it returns. Zig handles this for you.
  • The heap: memory you ask for while the program runs, from an allocator. It stays until you give it back.

Here’s the first one, global data:

const std = @import("std");
var visits: u32 = 0;
const greeting = "hello";
fn visit() void {
visits += 1;
}
pub fn main() void {
visit();
visit();
std.debug.print("{s}, you have {d} visits\n", .{ greeting, visits });
}

Output:

hello, you have 2 visits

visits and greeting are declared outside any function, so they live in the program’s global data from start to finish. visit can change visits, and main still sees the change. Globals are simple, but most of your data won’t live there: a global is shared by the whole program, which gets messy fast. The rest of this lesson is about the other two.

Picture a pile of cafeteria trays. Each time a function is called, Zig puts a new tray on top of the pile. The function’s local variables sit on that tray. When the function returns, its tray is taken off, and everything on it is gone. The tray underneath belongs to whoever called it.

You can watch the pile grow and shrink:

const std = @import("std");
fn level(n: u32) void {
std.debug.print("enter level {d}\n", .{n});
if (n < 3) level(n + 1);
std.debug.print("leave level {d}\n", .{n});
}
pub fn main() void {
level(1);
}

Output:

enter level 1
enter level 2
enter level 3
leave level 3
leave level 2
leave level 1

Each call to level gets its own tray with its own n. Level 3 is the top tray, so it’s the first one to leave. That’s why it’s called a stack: last on, first off.

The stack is fast, and you never have to clean it up. Zig does it the moment a function returns. That’s also its one big rule: a local variable is gone when its function returns. If you want to hand data back to the caller, return it by value, and Zig puts a copy where the caller can see it:

const std = @import("std");
fn makeRow() [3]u8 {
var row = [_]u8{ 'a', 'b', 'c' };
row[0] = 'A';
return row;
}
pub fn main() void {
var mine = makeRow();
mine[2] = 'C';
std.debug.print("{s}\n", .{&mine});
}

Output:

AbC

row was on makeRow’s tray, which is gone. But the three bytes were returned by value, so main has its own array in mine, on its own tray, and can change it as it likes.

The stack has two limits you’ll run into.

First, the size of everything on it must be known when the program compiles. Zig needs to know how big each tray is. So you can’t make a local array whose length is only known while running:

const std = @import("std");
pub fn main() void {
var count: usize = 5;
count += 1;
var scores: [count]u32 = undefined;
scores[0] = 1;
std.debug.print("{d}\n", .{scores[0]});
}
main.zig:6:18: error: unable to resolve comptime value
var scores: [count]u32 = undefined;
^~~~~
main.zig:6:18: note: types must be comptime-known

[count]u32 is a type, and types have to be known while compiling. count is only known while running (count += 1 makes sure of that), so Zig refuses.

Second, the stack is small. On our Linux machine it’s 8 MB for the main thread (ulimit -s prints 8192, in kilobytes). It’s different on other systems and for other threads. Put a 64 MB array on it and the program crashes as soon as the function starts:

const std = @import("std");
pub fn main() void {
var big: [64 * 1024 * 1024]u8 = undefined;
big[0] = 1;
std.debug.print("{d}\n", .{big[0]});
}

You’ll see something like:

Segmentation fault at address 0x7ffef554f510
main.zig:3:20: 0x11e3dbd in main (main.zig)
pub fn main() void {
^

Notice it doesn’t say “stack overflow”. It’s a plain segmentation fault pointing at the start of main, which is confusing the first time. If a function with a big local array crashes right at its first line, this is why.

When the size is only known while running, or the data has to outlive the function that made it, you use the heap. Think of it as a storage unit you rent: you ask for a unit of a certain size, you get a key (a slice), and the unit is yours until you hand the key back. Nobody else cleans it out for you.

In Zig you rent memory from an allocator. The easiest one to get is init.gpa, which main receives when you write pub fn main(init: std.process.Init) (more in Zig Main & Init):

const std = @import("std");
pub fn main(init: std.process.Init) !void {
const gpa = init.gpa;
var how_many: usize = 4;
how_many += 1; // pretend this number came from the user
const squares = try gpa.alloc(u64, how_many);
defer gpa.free(squares);
for (squares, 0..) |*sq, i| sq.* = i * i;
std.debug.print("{any}\n", .{squares});
}

Output:

{ 0, 1, 4, 9, 16 }

This is the program the stack couldn’t run. gpa.alloc(u64, how_many) asks for room for 5 u64s and gives back a slice, []u64. try is there because asking can fail: the computer might be out of memory (you’ll meet try properly in Zig Try & Catch). defer gpa.free(squares); hands the memory back when main ends, the pattern from Zig Defer.

The heap is more flexible than the stack: any size, any lifetime. The price is that you say when it ends. Forget the free and the memory stays rented until the program exits. That’s a memory leak, and Zig Memory Leaks shows how Zig helps you find them.

In Python, names.append("Ana") quietly asks for more memory when the list is full. In Go, the runtime decides whether a value goes on the stack or the heap. In Zig, nothing allocates behind your back. A function that needs heap memory takes an allocator as a parameter, so you can see it right in the call.

Here’s the same job done both ways. std.mem.print writes text into a buffer you give it; gpa.print rents heap memory for the text:

const std = @import("std");
pub fn main(init: std.process.Init) !void {
const gpa = init.gpa;
var buf: [32]u8 = undefined;
const on_stack = try std.mem.print(&buf, "{d} apples", .{3});
const on_heap = try gpa.print("{d} pears", .{5});
defer gpa.free(on_heap);
std.debug.print("{s} and {s}\n", .{ on_stack, on_heap });
}

Output:

3 apples and 5 pears

on_stack is a slice into buf, a 32-byte array on main’s tray: no allocator, nothing to free, but it can never hold more than 32 bytes. on_heap came from the allocator: it can be any length, but you must free it. Neither is “the right one”. Zig gives you both and lets you pick.

This is what the language reference’s Memory section means when it says there’s no default allocator in Zig: functions that allocate take one, and the caller decides which.

This function tries to hand back a slice of a local array, and Zig refuses to compile it. Change it so it returns the array itself, and print the result.

const std = @import("std");
fn countdown() []const u8 {
var digits = [_]u8{ '3', '2', '1' };
return &digits;
}
pub fn main() void {
std.debug.print("{s}\n", .{countdown()});
}

Hint: change the return type to [3]u8 and return digits;. In main, store the result in a const and print a slice of it with &.

Show solution
const std = @import("std");
fn countdown() [3]u8 {
const digits = [_]u8{ '3', '2', '1' };
return digits;
}
pub fn main() void {
const result = countdown();
std.debug.print("{s}\n", .{&result});
}

Output:

321

The three bytes are copied out to result in main, so it doesn’t matter that countdown’s tray is gone. digits is now const because nothing changes it.

Write a program that rents width bytes from init.gpa, fills them with =, and prints them. Make width a run-time value (start at 9 and add 1), and free the memory with defer.

Hint: try gpa.alloc(u8, width), then @memset(line, '='), then print with {s}.

Show solution
const std = @import("std");
pub fn main(init: std.process.Init) !void {
const gpa = init.gpa;
var width: usize = 9;
width += 1;
const line = try gpa.alloc(u8, width);
defer gpa.free(line);
@memset(line, '=');
std.debug.print("{s}\n", .{line});
}

Output:

==========

A stack array would need its length while compiling, so a run-time width means the heap.

Use std.mem.print to write "{d} bottles" with the number 99 into a buffer of only 4 bytes. Catch the error and print its name.

Hint: std.mem.print(&buf, ...) catch |err| { ... } and @errorName(err).

Show solution
const std = @import("std");
pub fn main() void {
var buf: [4]u8 = undefined;
const text = std.mem.print(&buf, "{d} bottles", .{99}) catch |err| {
std.debug.print("error: {s}\n", .{@errorName(err)});
return;
};
std.debug.print("{s}\n", .{text});
}

Output:

error: NoSpaceLeft

A stack buffer has a fixed size, and std.mem.print tells you when the text doesn’t fit instead of writing past the end. That’s the trade: no allocator, but a hard limit.

  • Every value lives in global data, on the stack, or on the heap. Keep asking “where are the bytes?”
  • The stack holds a function’s local variables. It’s fast and cleaned up automatically when the function returns.
  • Stack sizes must be known while compiling, and the stack is small (8 MB on our Linux machine). Too much gives a plain segfault.
  • Return data by value, never as a pointer or slice into a local.
  • The heap is memory you rent from an allocator: any size, any lifetime, and you free it.
  • Zig has no hidden allocations: a function that needs heap memory takes an allocator.

Next up: Zig Allocators, what an allocator is and the handful of calls you’ll use every day.

Quick check

1. Where does a local variable inside a function live?
2. You need an array whose length the user types in. Where does it go?
3. Why do Zig functions that need heap memory take an allocator parameter?
4. A function with a 64 MB local array crashes right at its first line. What is the likely cause?