liveBook · Manning

Dangling pointer

As explained in Systems Programming with Zig

A dangling pointer is a pointer that retains an address after the data formerly stored there is no longer valid.

A pointer is an address, not proof that valid data still exists there. It dangles when the data at that address has been released or otherwise ceased to be valid. section 5.3.3

How a pointer dangles

Free the memory a pointer addresses, then dereference it; or return a pointer to a function’s stack variable. Either can cause a segmentation fault or leave the program corrupted. section 5.3.3

For recipe strings, use storage that outlives the recipe, such as a string literal, or duplicate the string when user-managed storage is unsuitable. 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 duplicates a C string into the recipe book’s string arena. section 5.3.3

How Systems Programming with Zig covers it

How deep it goes
Defines dangling pointers, explains two failure cases, and stops short of a general prevention procedure.
Examples
Shows dereferencing freed memory, returning a stack-variable pointer, and duplicating recipe strings.
What you can do after
Evaluate whether recipe strings outlive their use and duplicate them when user-managed storage is unsuitable.
How it connects
Connects pointers with memory lifetimes, stack variables, C strings, and string duplication.

Also explained in

Compare how 3 books explain dangling pointer →

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.