Memory allocation in linked list

Hi @thilina, welcome to ziggit! :slight_smile:

In the insert function var newNode = Node{ .val = v }; allocates Node storage from the hardware stack. The stack position is restored when insert returns.
That means that the lifetime of Node ends when function exits.
The pointer to Node returned by &newNode points to an address that is replaced by other contents, depending on what runs next.

In zig an allocator is a programming interface that you can use to request memory allocation (by calling allocator.alloc) and release the memory when it is not used (by calling allocator.free).
There are various allocators, the GeneralPurposeAllocator might be your first choise, but you can also use an ArenaAllocator; in ArenaAllocator you can call alloc and when you are done with all the allocations you can call deinit to free the entire arena with all the allocations.

You can find allocation documentation and examples in the Zig Learning Resources.

3 Likes