Allocators: Best Practices & Anti-Patterns

I understand allocation should be explicit and not implicit, and generally pass my allocators down through function calls so that the caller can handle the call to free the memory (while using errdefer to ensure errors don’t cause leaks). I have looked around for blog posts or documentation regarding anti-patterns and best practices beyond the call for explicit memory management, but have not found anything beyond “pass allocators as function arguments”. Does anyone have any great resources for common pitfalls with allocations and how best to avoid them? I want to ensure I’m doing things in an idiomatic fashion.

I think the main reason while you find no clean list on this is because the answer is diverse.
Even the “always pass down the allocator”, is not as strict as you think it is. It makes a lot of sense for libraries and simple data structures, but when it comes to your application it makes sense to e.g. commit to a single global allocator or commit to always pass arena’s to this function.

To give some examples: For short running CLI tools the general recommendation is to just use an arena for everything. On the other end of the spectrum, my project Cubyz (a game) uses a variety of different arenas and a global and a stack-local allocator with different use-cases as stated in the project guidelines.

If you are in doubt then I’d generally recommend to use the DebugAllocator. It will be good enough for most cases and gives you more guardrails (→leak detection) which help when you are new to manual memory management. And beyond that, I’d suggest to keep your eyes out for arena allocators, they can save a lot of complexity in your code.

Apart from that a few general tips:
Try to avoid creating many objects with complex lifetimes and reference counting. Instead try grouping objects of similar lifetime into arenas or use a more data oriented approach.
Here are also some related posts I’d suggest to check out for more practical examples:

2 Likes

There were a couple recent threads discussing different aspects of this question.

2 Likes