liveBook · Manning

Ownership

As explained in Systems Programming with Zig

Memory ownership is the responsibility for managing the lifetime and eventual release of allocated memory.

When a recipe is created, its input strings are not copied: the caller remains responsible for managing their memory. Pass strings that outlive the recipe, or duplicate them into the recipe book’s string arena. section 5.3.3

Memory outlives other memory when it is released later. If a pointer’s memory is freed first, the pointer becomes dangling: it still holds an address, but the data there is no longer valid. section 5.3.3

Listing 5.6 Duping C strings
fn dupeCString(
    self: *RecipeBook,
    cstr: [*:0]const u8,
) Allocator.Error![:0]const u8 {
    const arena_ally = self.string_arena.allocator(); #1
    const slice = std.mem.span(cstr); #2
    return try arena_ally.dupeZ(u8, slice); #3
}

This helper copies a null-terminated C string into the recipe book’s string arena. section 5.3.3

How Systems Programming with Zig covers it

How deep it goes
Explains uncopied input strings, outliving memory, dangling pointers, and arena-based duplication.
Examples
Contrasts passing long-lived recipe strings with duplicating C strings into a string arena.
What you can do after
Apply lifetime choices by passing strings that outlive a recipe or duplicating them into its string arena.
How it connects
Connects ownership to lifetimes, allocators, string arenas, and dangling pointers.

Also explained in

Compare how 8 books explain ownership →

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.