liveBook · Manning

Lifetime

As explained in Systems Programming with Zig

A lifetime is the period during which a program's data remains valid and available in storage.

An arena allocator gives its allocations a shared lifetime: recipe and ingredient strings can remain valid for as long as their recipe book object. section 5.3.2

Listing 5.4 Giving the recipe book blank pages to fill
const std = @import("std");
const Allocator = std.mem.Allocator;

const RecipeId = enum (c_int) { _ };

const RecipeBook = struct {
    const Recipe = struct {
        name: [:0]const u8,
        author: [:0]const u8,
        instructions: [:0]const u8,
    };

    const Ingredient = struct {
        recipe_id: RecipeId,
        quantity: [:0]const u8,
        name: [:0]const u8,
    };

    string_arena: std.heap.ArenaAllocator,
    recipes: std.AutoHashMapUnmanaged(RecipeId, Recipe),
    ingredients: std.ArrayList(Ingredient),

    fn init(ally: Allocator) RecipeBook { #1
        return .{
            .string_arena = .init(ally),
            .recipes = .empty,
            .ingredients = .empty,
        };
    }

    fn deinit(self: *RecipeBook, ally: Allocator) void { #2
        self.string_arena.deinit(); #3
        self.recipes.deinit(ally); #3
        self.ingredients.deinit(ally); #3
    }
};

The recipe book structure pairs a string arena with its recipe and ingredient data. section 5.3.2

How Systems Programming with Zig covers it

How deep it goes
Explains how an arena groups allocations under one lifetime, without detailing allocator internals.
Examples
Uses recipe and ingredient strings that remain allocated with the recipe book.
What you can do after
Apply arena allocation to keep related strings alive for the recipe book object's lifetime.
How it connects
Connects lifetimes to arena allocators, allocators, and manual memory management.

Also explained in

Compare how 9 books explain lifetime →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Systems Programming with Zig. The section links point to the parts of the book it draws on.