Field Lifetime of Heap-Allocated Struct

Is &Node{ .atom = 0} a dangling pointer here or does it share the lifetime of its parent Node?

fn exprBindingPower(allocator: std.mem.Allocator, ... ) *Node {
    var left_ptr = allocator.create(Node) catch unreachable;
    left_ptr.* = switch (lexer_ptr.next()) {
        .atom => |ch| Node{ .atom = ch },
        .op => |op| blk: {
            const bp = BindingPower.prefix(op);
            const right_ptr = exprBindingPower(...);

            break :blk Node{
                .cons = .{
                    .left = &Node{ .atom = 0 }, // dubious lifetime 
                    .op = op,
                    .right = right_ptr,
                },
            };
        },
        // ...
    };

    // ...

    return left_ptr;
}

Correct me if I’m wrong, .left = Node{ .atom = 0 } here has a static lifetime so problem solved.

Here’s the declaration.

const Node = union(enum) {
    atom: u8,
    cons: struct {
        op: u8,
        left: *const Node,
        right: *const Node,
    },
}
1 Like

You are right. It is a pointer to statically allocated memory.

1 Like