Skip to content
Tutorials Center
My learning

Topics

Lesson 19 of 37 ยท Types and Memory

Memory Layout and Alignment

Understand where Zig values live: stack versus heap, sizes and alignment with @sizeOf and @alignOf, padding, extern struct for C layout, packed struct for bits, and how to read memory safely.

To write systems code you need a mental map of memory: where values live, how big they are, and how they are arranged. Zig exposes all of this through a few builtins, so you can measure instead of guess. This lesson closes the Types and Memory chapter and prepares you for allocators in the next one.

Stack and heap

Two regions matter for most programs:

  • The stack holds local variables and function arguments. It is fast and managed automatically: space appears when a function is called and disappears when it returns. Size is limited (typically a few megabytes), and nothing on it may outlive its function.
  • The heap holds memory you request at runtime from an allocator. It can be large and can live as long as you like, but you must free it, and getting it is slower.

Static data (string literals, global consts) lives in the program image for the program's whole life.

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

var global_counter: u32 = 0;                 // static storage, whole program

pub fn main() !void {
    const literal = "static text";           // static, read-only
    var on_stack: [64]u8 = undefined;        // stack: freed automatically
    _ = &on_stack;

    const gpa = std.heap.page_allocator;
    const on_heap = try gpa.alloc(u8, 1024); // heap: YOU must free it
    defer gpa.free(on_heap);

    global_counter += 1;
    std.debug.print("{s}, {d}\n", .{ literal, global_counter });
}

Rule of thumb: use the stack for small, short-lived data whose size you know at compile time, and the heap when the size is dynamic or the data must outlive the function. Because Zig never allocates implicitly, every heap allocation in your program appears as an explicit call on an allocator.

Where does it live?

Stack Locals. Automatic, fast, limited, dies with the function
Heap Allocator calls. Flexible size and lifetime, you free it
Static Literals and globals. Live for the whole program

Never return a pointer to stack memory.

1 / 2

Measuring: @sizeOf, @alignOf, @bitSizeOf

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

pub fn main() void {
    std.debug.print("u8:    size {d}, align {d}\n", .{ @sizeOf(u8), @alignOf(u8) });
    std.debug.print("u32:   size {d}, align {d}\n", .{ @sizeOf(u32), @alignOf(u32) });
    std.debug.print("f64:   size {d}, align {d}\n", .{ @sizeOf(f64), @alignOf(f64) });
    std.debug.print("u3 bits {d}, size {d}\n", .{ @bitSizeOf(u3), @sizeOf(u3) });
    std.debug.print("[10]u16 size {d}\n", .{@sizeOf([10]u16)});
    std.debug.print("slice size {d}\n", .{@sizeOf([]const u8)});
}

On a 64-bit machine this prints:

TEXT
u8:    size 1, align 1
u32:   size 4, align 4
f64:   size 8, align 8
u3 bits 3, size 1
[10]u16 size 20
slice size 16

A slice is 16 bytes: an 8-byte pointer plus an 8-byte length. A u3 has 3 meaningful bits but occupies one byte when stored alone.

Alignment and padding

CPUs prefer values at addresses that are multiples of their size: a u32 at an address divisible by 4, an f64 divisible by 8. That requirement is the type's alignment. To maintain it, compilers insert padding bytes between fields.

Consider fields a: u8, b: u32, c: u8. If laid out in declaration order, a sits at offset 0, 3 bytes of padding follow, b sits at 4, c at 8, and the struct is padded at the end to a multiple of 4, giving 12 bytes for 6 bytes of data. Reordered as b, a, c, it needs only 8.

A normal Zig struct has no guaranteed field order: the compiler is free to reorder fields to minimize padding, so its size can be smaller than the C equivalent. That is why you cannot rely on layout of plain structs.

extern struct: C layout

An extern struct uses the C ABI's rules exactly: fields in declaration order with C padding. Use it when passing data to C, to files, or over the network where both sides must agree:

ZIG
const Header = extern struct {
    kind: u8,
    length: u32,
    flags: u8,
};
// @sizeOf(Header) == 12 on common platforms, the same as the C struct

packed struct: bit-level layout

A packed struct has no padding, and fields are packed bit by bit, in order from the least significant bit. Fields can be any integer width, bool (1 bit) and enums. Packed structs have a backing integer, so you can convert to and from it:

ZIG
const Permissions = packed struct(u8) {
    read: bool,
    write: bool,
    execute: bool,
    owner: u3,          // value 0 to 7
    _unused: u2 = 0,
};

pub fn main() void {
    const p = Permissions{ .read = true, .write = true, .execute = false, .owner = 5 };
    const raw: u8 = @bitCast(p);
    std.debug.print("raw = 0b{b:0>8}\n", .{raw});
}

The bits from lowest: read=1, write=1, execute=0, owner=101 (bits 3 to 5), unused=00, so the byte is 00101011. @bitCast reinterprets without changing bits. Packed structs are perfect for hardware registers, protocol flags and compact tables; they replace C bitfields with well-defined behavior.

Reading bytes: endianness

Multi-byte numbers are stored low byte first on x86 and ARM (little-endian) and high byte first in many network formats (big-endian). std.mem.readInt(u32, bytes[0..4], .little) and .big read with an explicit order, std.mem.writeInt writes. Always specify endianness when parsing files or network data.

Alignment in pointers

A pointer type includes alignment: *u32 is *align(4) u32. A byte buffer is only aligned for u8, so casting it to *u32 would be unsound. Use std.mem.readInt on a slice, or @alignCast when you know the address is aligned. @ptrCast alone to a more strictly aligned type is a compile error, and the message names align(1) versus align(4).

The size of everything else

  • bool, u8, i8: 1 byte. Enums: the smallest integer that fits their fields.
  • Optionals ?T: the size of T plus a flag, usually padded; ?*T is pointer-sized.
  • Tagged unions: the largest payload plus the tag, with padding.
  • Arrays [N]T: N * @sizeOf(T). Slices: two words.
  • usize and pointers: 8 bytes on 64-bit targets, 4 on 32-bit.

Measure with @sizeOf; in tests you can pin the answer with try std.testing.expectEqual(8, @sizeOf(Foo)); so a layout change fails loudly.

Stand-ins you can run

C reports the same sizes and padding. This stand-in measures the three-field struct in both orders and shows a manual bit-packed permissions byte equal to the Zig packed struct example.

C Stand-in (C): sizeof, alignment, padding and bit packing

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Rust shows the same layout facts, including how reordering shrinks a struct, which is also what Zig does for plain structs:

Rust Stand-in (Rust): size_of, align_of and field reordering

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Where do local variables live?

    Locals live on the stack and disappear when the function returns.
  2. 2. What does @sizeOf([]const u8) return on a 64-bit machine?

    A slice stores an 8-byte pointer and an 8-byte length.
  3. 3. Which struct kind guarantees C-compatible layout?

    extern struct follows the C ABI field order and padding rules.
  4. 4. What is a packed struct good for?

    Packed structs place fields bit by bit and can convert to a backing integer with @bitCast.
  5. 5. Why is a plain Zig struct smaller than the C struct with the same fields, sometimes?

    Plain structs have unspecified layout, so the compiler can reorder them to save space.

Summary

  • Stack for locals, heap through allocators for dynamic or long-lived data, static for literals and globals.
  • @sizeOf, @alignOf and @bitSizeOf measure instead of guess; a slice is two words.
  • Alignment forces padding; plain structs may be reordered, extern struct follows C, packed struct packs bits.
  • @bitCast reinterprets bits; use std.mem.readInt with an explicit endianness for bytes.
  • Pointer types include alignment; casts to stricter alignment need @alignCast.

Next: Allocators in Zig