Where are the bytes

for Zig 0.15.2 Buy

Where are the bytes

This is a very interesting question, also asked in Zig’s official documentation: Where are the bytes. By the way, I recommend checking out the official docs whenever you have questions, or just to learn more about Zig.

Below you can see a memory diagram of a Zig program:

Memory diagram in a Zig program

The memory used by a Zig program is split into three clearly distinct parts:

Compile-time memory

At the base of the program is compile-time memory. This part of memory holds everything Zig knows before running the program: code, literal data, constant values, and anything evaluated at comptime. It’s included in the final binary, ready to be loaded into memory when the program starts. It’s a predictable area as it doesn’t change during execution because its contents were defined ahead of time.

Stack

On a stack, we can imagine data stacked like boxes, one on top of another. You can only access it from the top. We call this access policy LIFO (Last In, First Out)- the last item in is the first one out.  The stack is fast and is used to store small-sized values. It’s located at the upper part of the program’s memory and grows downward. When data is released, the stack shrinks and takes up less memory.

When we declare a variable or constant whose value isn’t known at compile time, but its size is known, Zig can use the stack to store it.

That said, even if the size is known, we can use the stack, but we shouldn’t always do it. The stack has limited space. If we store large structures or make many recursive calls, we could cause a stack overflow.

We already saw an example of uncontrolled stack growth in the section: Loops / Recursion, with a function that called itself without a stop condition:

recursive_infinite.zig

fn infinite_loop() void {

    infinite_loop();

}

pub fn main() void {

    infinite_loop();

}

$ zig run recursive_infinite.zig

Segmentation fault (core dumped)

Each recursive call is assigned a frame (a dedicated block of memory) on the stack. The size of that frame depends on the operating system and its resource management. Even if each frame is small, when repeated thousands of times, they stack up one after another until the program tries to access a memory area outside its allocated stack space. That triggers a segmentation fault, and the operating system kills the process.

Heap

The Heap (dynamic memory) is the area of memory used to store data whose size isn’t known until the program is running. This happens, for example, when we load a file, read keyboard input, or generate dynamic data structures. The heap is slower but much larger than the stack.

If we need space, we request it at runtime. If memory is available, the system grants it. If not, we’ll get an error, and we’ll have to handle it properly.

Unlike the stack, the heap grows upward, from lower to higher memory addresses.

Memory and Strings
Memory timing
© 2025 - 2026 Zen of Zig