Skip to content

Zig Lifetimes & Ownership

Every piece of memory has a lifetime: the stretch of time when it’s valid to use. And every piece of heap memory needs an owner: the one part of your code that will free it. Rust checks both of these for you while compiling. Zig doesn’t. In Zig, ownership is a set of habits and naming conventions that you keep, with some help from the checking allocator at run time. That sounds risky, and it does take care, but the conventions are few and the whole standard library follows them. Once you know them, reading any Zig code tells you who frees what.

You’ve met all four kinds of lifetime already:

Where the memory came from Valid until
A string literal or a top-level const/var The program ends
A local variable (the stack) The function or block returns
alloc or create from an allocator You free or destroy it
An arena The arena’s deinit or reset

A dangling pointer or slice is one that outlives the memory it points at. It still looks fine (it’s just an address and a length), but the memory behind it now belongs to something else, or to nobody. Reading through it gives garbage, and writing through it can quietly break other data. Almost every ownership bug is a dangling slice or pointer in disguise.

Here’s the mistake almost everyone makes once. The function builds a list in a local array and returns a slice of it:

const std = @import("std");
fn makeList() []const u32 {
var nums = [_]u32{ 1, 2, 3, 4 };
const view: []const u32 = &nums;
return view;
}
fn noise() u64 {
var junk = [_]u64{ 111, 222, 333, 444 };
_ = &junk;
return junk[0];
}
pub fn main() void {
const list = makeList();
_ = noise();
std.debug.print("{any}\n", .{list});
}

When we ran this in a debug build, it printed:

{ 11184810, 170, 444, 0 }

and in a fast build, { 0, 0, 0, 0 }. Neither is { 1, 2, 3, 4 }. nums lived on makeList’s part of the stack. As soon as makeList returned, that space was free, and noise reused it for its own local. list still points there, so it shows whatever happens to be there now. (11184810 is 0xaaaaaa, the “undefined” pattern debug builds use.)

Zig catches the direct version, return &nums;, as a compile error (“returning address of expired local variable”). But here the slice went through a variable first, and that compiles fine. The compiler can’t catch every dangling slice, so the rule is yours to keep.

There are three ways to fix it, and you’ll use all three.

If the data is small and its size is known while compiling, return it by value. The caller gets its own copy:

const std = @import("std");
fn makeList() [4]u32 {
return .{ 1, 2, 3, 4 };
}
pub fn main() void {
const list = makeList();
std.debug.print("{any}\n", .{list});
}

Output:

{ 1, 2, 3, 4 }

If the size isn’t fixed but has a sensible limit, let the caller own the memory. The caller passes a buffer, and the function fills part of it and returns a slice of that part. Here the buffer lives in main, so the slice is valid for as long as main runs:

const std = @import("std");
fn formatScore(buf: []u8, name: []const u8, score: u32) ![]u8 {
return std.mem.print(buf, "{s}: {d} points", .{ name, score });
}
pub fn main() !void {
var buf: [64]u8 = undefined;
const line = try formatScore(&buf, "Ana", 120);
std.debug.print("{s}\n", .{line});
}

Output:

Ana: 120 points

No allocator, nothing to free, and the lifetime is plain to see: line is good as long as buf is. The standard library uses this shape a lot (std.mem.print, the buffers you give to readers and writers).

If the size can be anything, or the result has to live a long time, allocate it. The function takes an allocator, and the caller owns what comes back:

const std = @import("std");
/// Caller owns the returned memory.
fn makeList(gpa: std.mem.Allocator, n: usize) ![]u32 {
const nums = try gpa.alloc(u32, n);
for (nums, 1..) |*x, i| x.* = @intCast(i);
return nums;
}
pub fn main(init: std.process.Init) !void {
const gpa = init.gpa;
const list = try makeList(gpa, 4);
defer gpa.free(list);
std.debug.print("{any}\n", .{list});
}

Output:

{ 1, 2, 3, 4 }

This is the first convention to remember: when a function takes an allocator and returns memory, the caller owns it and must free it, with the same allocator. Good Zig code says so in a doc comment, like /// Caller owns the returned memory. above. You’ll see that exact sentence all over the standard library.

When a function takes a []const u8 parameter, it’s borrowing: it can look at the text while it runs, and that’s all. If it wants to keep the text for later, it must make its own copy. Here’s what happens when it doesn’t:

const std = @import("std");
pub fn main() !void {
const inputs = [_][]const u8{ "ana", "bob", "cyd" };
var buf: [16]u8 = undefined;
var saved: [3][]const u8 = undefined;
for (inputs, 0..) |name, i| {
const line = try std.mem.print(&buf, "user {s}", .{name});
saved[i] = line;
}
for (saved) |s| std.debug.print("{s}\n", .{s});
}

Output:

user cyd
user cyd
user cyd

Each round writes into the same buf. saved doesn’t hold three strings; it holds three slices of one buffer, which by the end says user cyd. Nothing is freed here, so no checker complains. It’s just wrong. This happens in real programs that read lines into a reused buffer and store the slices.

The fix is to own a copy. A struct that keeps text should dupe it in init and free it in deinit. That’s the second convention: a type that owns memory has a deinit(allocator) method, and whoever made the value calls it.

const std = @import("std");
const Person = struct {
name: []u8,
age: u8,
/// Copies `name`. Call `deinit` with the same allocator when done.
fn init(gpa: std.mem.Allocator, name: []const u8, age: u8) !Person {
return .{ .name = try gpa.dupe(u8, name), .age = age };
}
fn deinit(self: Person, gpa: std.mem.Allocator) void {
gpa.free(self.name);
}
};
pub fn main(init: std.process.Init) !void {
const gpa = init.gpa;
var buf: [16]u8 = undefined;
const typed = try std.mem.print(&buf, "{s}", .{"Ana"});
const ana: Person = try .init(gpa, typed, 31);
defer ana.deinit(gpa);
@memcpy(buf[0..3], "XXX");
std.debug.print("{s} is {d}\n", .{ ana.name, ana.age });
}

Output:

Ana is 31

typed is a borrowed slice of buf. Person.init copies it, so when buf is overwritten with XXX, ana.name doesn’t care. ana owns its name, and defer ana.deinit(gpa) frees it.

This is exactly how std.ArrayList works: var list: std.ArrayList(u8) = .empty; then defer list.deinit(gpa);. The allocator is passed to deinit because the list doesn’t store it; you give it the same one you used for append.

Copying a struct copies its fields. For a slice field, that copies the pointer, not the bytes. So after const copy = ana;, both ana.name and copy.name point at the same memory. If both think they own it, both free it:

const std = @import("std");
const Person = struct {
name: []u8,
fn deinit(self: Person, gpa: std.mem.Allocator) void {
gpa.free(self.name);
}
};
pub fn main(init: std.process.Init) !void {
const gpa = init.gpa;
const ana: Person = .{ .name = try gpa.dupe(u8, "Ana") };
defer ana.deinit(gpa);
const copy = ana;
defer copy.deinit(gpa);
std.debug.print("{s} {s}\n", .{ ana.name, copy.name });
}

You’ll see something like:

Ana Ana
thread 1975 panic: double free of [addr: 7fc37fead968, len: 3 (0x3) align: 1]
alloc:
...
main.zig:14:48: 0x11e41f3 in main (main.zig)
const ana: Person = .{ .name = try gpa.dupe(u8, "Ana") };
^
first free:
main.zig:7:17: 0x11ef1d8 in deinit (main.zig)
gpa.free(self.name);
^
main.zig:18:22: 0x11e431c in main (main.zig)
defer copy.deinit(gpa);
^
second free:
...
main.zig:7:17: 0x11ef1d8 in deinit (main.zig)
gpa.free(self.name);
^
main.zig:15:21: 0x11e4350 in main (main.zig)
defer ana.deinit(gpa);
^

We trimmed it, but every part is useful. In debug builds, init.gpa remembers each allocation and refuses to free it twice. The panic shows where it was allocated, where it was first freed (copy’s deinit, since defers run newest first) and the second free (ana’s). In a fast build there’s no check, and a double free can corrupt the allocator and crash much later, somewhere unrelated.

The fix is to decide on one owner. Either only ana calls deinit, and copy is just a borrowed view, or copy gets its own memory with gpa.dupe.

The other ownership bug is using memory after its owner freed it:

const std = @import("std");
pub fn main(init: std.process.Init) !void {
const gpa = init.gpa;
const scores = try gpa.alloc(u32, 3);
scores[0] = 10;
gpa.free(scores);
scores[0] = 99;
std.debug.print("score: {d}\n", .{scores[0]});
}

You’ll see something like:

score: 99
thread 30337 panic: write after free at *7f6a14637968
original alloc of [addr: 7f6a14637968, len: 12 (0xc) align: 4]:
main.zig:5:33: 0x11e41ea in main (main.zig)
const scores = try gpa.alloc(u32, 3);
^
free:
main.zig:7:13: 0x11e42e9 in main (main.zig)
gpa.free(scores);
^

Notice that score: 99 printed first. The write itself didn’t crash. The checking allocator fills freed memory with a known pattern and checks it later, here when the program ends, and finds the pattern changed. So the panic tells you which allocation was written after being freed and where it was freed, but not the exact line that wrote to it. That’s usually enough to find it. Reading after free is quieter still: try it, and you’ll see 1431655765, which is 0x55555555, the fill pattern.

The 0.17.0 release notes are honest about this: most writes after free “will segmentation fault or are eventually detected”. The checks catch a lot, not everything. The habits below are what really keep you safe.

The language reference on lifetime and ownership puts it simply: it’s the programmer’s job to make sure a pointer isn’t used after the memory it points to is gone, and functions should document who owns what. In practice that means:

  • Caller owns returned memory. A function that takes an allocator and returns a slice or pointer hands ownership to the caller. Free it with the same allocator.
  • Parameters are borrowed. A []const u8 you’re given is only good while the call runs. To keep it, dupe it.
  • Types that own memory have deinit. Usually deinit(self, allocator), called by whoever made the value, often with defer right after init.
  • One owner per allocation. Copies of a struct share its slices. Only one of them may free.
  • Write it down. A short doc comment (/// Caller owns the returned memory., /// Copies name.) saves the next reader from guessing.
  • Watch for slices into growing things. list.items from an ArrayList is only valid until the list grows again (the reference uses this exact example). Don’t hold on to it across an append.
  • Free in reverse. Free things in the opposite order you made them, which defer does for you.

Write fn greet(buf: []u8, name: []const u8) ![]u8 that writes "Hello, <name>!" into buf and returns the filled part. Call it from main with a 32-byte buffer.

Hint: the body is one line with std.mem.print.

Show solution
const std = @import("std");
fn greet(buf: []u8, name: []const u8) ![]u8 {
return std.mem.print(buf, "Hello, {s}!", .{name});
}
pub fn main() !void {
var buf: [32]u8 = undefined;
const text = try greet(&buf, "Bo");
std.debug.print("{s}\n", .{text});
}

Output:

Hello, Bo!

main owns buf, so the returned slice is valid as long as main is running. The function never needed an allocator.

Fix the “borrowed vs owned” example so it prints user ana, user bob and user cyd. Use init.gpa to dupe each line into saved, and free all three at the end.

Hint: saved[i] = try gpa.dupe(u8, line);, and after the loop, defer for (saved) |s| gpa.free(s);.

Show solution
const std = @import("std");
pub fn main(init: std.process.Init) !void {
const gpa = init.gpa;
const inputs = [_][]const u8{ "ana", "bob", "cyd" };
var buf: [16]u8 = undefined;
var saved: [3][]const u8 = undefined;
for (inputs, 0..) |name, i| {
const line = try std.mem.print(&buf, "user {s}", .{name});
saved[i] = try gpa.dupe(u8, line);
}
defer for (saved) |s| gpa.free(s);
for (saved) |s| std.debug.print("{s}\n", .{s});
}

Output:

user ana
user bob
user cyd

Each dupe makes an owned copy, so overwriting buf no longer matters. defer can take a whole for loop, which frees all three at the end.

Make a struct Book with title: []u8 and author: []u8, an init(gpa, title, author) that copies both, and a deinit(self, gpa) that frees both. Create one in main, print it, and make sure there’s no leak report.

Hint: if the second dupe fails, the first one leaks. Use errdefer after the first.

Show solution
const std = @import("std");
const Book = struct {
title: []u8,
author: []u8,
fn init(gpa: std.mem.Allocator, title: []const u8, author: []const u8) !Book {
const t = try gpa.dupe(u8, title);
errdefer gpa.free(t);
const a = try gpa.dupe(u8, author);
return .{ .title = t, .author = a };
}
fn deinit(self: Book, gpa: std.mem.Allocator) void {
gpa.free(self.author);
gpa.free(self.title);
}
};
pub fn main(init: std.process.Init) !void {
const gpa = init.gpa;
const book: Book = try .init(gpa, "Dune", "Frank Herbert");
defer book.deinit(gpa);
std.debug.print("{s} by {s}\n", .{ book.title, book.author });
}

Output:

Dune by Frank Herbert

Book owns both strings, so deinit frees both, in reverse order. The errdefer makes sure a failure halfway through init doesn’t leak the title.

  • A lifetime is how long memory is valid; a dangling slice or pointer outlives its memory.
  • Never return a slice of a local. Return a value, fill a caller’s buffer, or allocate and let the caller own it.
  • Caller owns returned memory; parameters are borrowed, so dupe what you want to keep.
  • Types that own memory get deinit(allocator), and each allocation has exactly one owner.
  • In debug builds, double frees panic with all three stack traces, and writes after free are caught later.
  • The checks help, but the conventions are what keep your code correct.

Next up: Zig Result Location Semantics, a short look at how const x: T = .{...} knows what to build and where.

Quick check

1. A function returns &buf as a []const u8, where buf is a local array, but through a variable so it compiles. What happens?
2. A function takes name: []const u8 and wants to store it in a struct for later. What should it do?
3. You copy a struct that has a []u8 field: const b = a;. Then both call deinit. What does init.gpa do in a debug build?
4. Which doc comment tells you that you must free a function's result?