Nesting memory allocators

imagine that fxnA() wants to call fxnB(); and that both functions rely upon heap-allocated memory during their lifetimes…

until now, i’ve been using a single std.heap.ArenaAllocator across my command-line apps… but i have a use-case in which i really do want free all heap memory consumed by fxnB() upon its return to fxnA()

how do i approach this in general??? said another way, can i implement a “mark-and-release” pattern using a single allocator, or do i somehow stack them???

You can just create a separate arena allocator using the first one.

That being said, if these nested calls are not long running and/or use large amounts of memory, it’s probably not worth it. That depends on your use case.

You can chain ArenaAllocators.
When fxnA() calls fxnB() pass a new inner ArenaAllocator inited with child_allocator as the outer ArenaAllocator. Upon return of fxnB() deinit the inner allocator.
If this is in a loop, look at reset method documentation.

2 Likes

Also, if you know upper limit, you can allocate some chunk of memory (using either that arena or even with gpa) and then use fixed buffer allocator which is even simpler/faster than separate arena.