#Custom free method?

1 messages · Page 1 of 1 (latest)

native sonnet
#

I have a tree data structure, that has functions to create different nodes. Those functions take an allocator and create a node pointer and do all the stuff internally. This works and using an arena allocator it’s easy to clear the whole tree.

But what if I don’t want to use an arena? I would have to recursively go through the tree and destroy every node, which makes sense, since it’s basically reversing the create calls. Is there an idiomatic way to make this easier/simpler? My guess would be to write a function inside the nodes .destory(self: *Node, alloc: Allocator) or something similar and then they do the destroy calls recursively themselves, hidden away. While would likely work, I was just wondering what the „zig-way“ would be

hexed hatch
#

its usually called deinit and should return void. it can take an allocator to do the freeing. beware of stack overflow if you recurse over the tree because trees can be lineary deep.

jade socket
#

If you know enough about the usage of the tree, you could allocate using an object pool, which still permits you to destroy all the nodes easily and quickly, but only allocates blocks of a specific number of bytes, and may allow random order freeing.

#

I might also make it so that a node only destroys itself, and then you have a destroyTree function that does the recursion.

native sonnet
#

For my use case, an arena is likely still the best option, but thanks for the insights. I just wondered if there is a „standard“ way to do this in a (recursive) data-structure

#

In my case, the tree is described only by its nodes, so the root node basically is the tree. Maybe the deinit function would be better suited for a container structure „tree“ that holds and manages the tree instead of leaving it to the user of the tree to manage it