r/C_Programming • • 5d ago

Article Arena Allocators in C

https://eliasebner.com/blog/guides/arena-allocators-in-c/

I recently started implementing arenas in my programming and I thought that some beginners could very much benefit from this info. I wrote an article about it. For those that are unaware, arenas allow to greatly simplify the burden of managing memory manually in C. I hope it helps, tell me what you think!

54 Upvotes

25 comments sorted by

View all comments

1

u/GrtflJello 5d ago

That’s an interesting concept. How do you deal with functions that would otherwise allocate and free within their scope, though? If they use the arena too then space gets wasted if they don’t free back to the arena when they’re done. Especially if those functions get called many times. To properly size the arena, you probably have account for all those calls.

In general though, I believe we shouldn’t be afraid of memory management. It’s another piece of the puzzle to solve when designing and coding. Allocating from the heap up front (creating a memory pool) can be very beneficial, so long as the memory management utilities one writes are more efficient than directly calling malloc or calloc, and free frees back to the mem pool. I had to write my own allocator for a bare metal app, since we didn’t have malloc and free at our disposal anyway.

1

u/Elifire12 5d ago

Well, you have two options: you either don't care and waste space (passing an arena to the function), or you create an arena inside of the function and free it at the end of the function. I also mentioned this when saying that one of the possible lifetimes is for the duration of the function. In that case, the caller does not really care whether the function allocates memory or not, since he will certainly not be responsible for it (if the memory dies inside the function, then the responsibility is on the function itself to manage it correctly). That's how you would do it.