r/C_Programming • u/Elifire12 • Oct 13 '26
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!
55
Upvotes
18
u/LeeHide Oct 13 '26
Good article, the only caveat is that saying that "allocating small chunks is slow" is not really good in an article that should teach something. This is the kind of sentence that is taught with no real context, and then people avoid allocations thinking they are slow!
Nothing is slow until it's measured to be slow. Measure, and if allocations dominate in your profile, then it's slow. Otherwise, its fast enough to allocate.
2
u/WSWhitehouse Oct 13 '26
Interesting read, I've used arenas for a while now and haven't looked back!
Your
arena_reallocfunction is not something I've considered before - I am curious how often you use this in practice? I wonder if you could also add some logic to check if thesrcptr was the last memory allocated on the arena and simply grow it without performing a whole new allocation? Would in theory avoid any unnecessary unused memory in your arena memory block.You should definitely take a look into Virtual Memory if you haven't already. Seriously takes arenas to the next level!
18
u/Silver-North1136 Oct 13 '26
One neat thing you can do with arena allocators, and when dealing with memory this way in general, is that you can map (mmap/VirtualAlloc) way more memory than you'll ever realistically need at the start of your program, and none of it will actually be used until you touch the page it's in. Trying to make it dynamically resize on the other hand will require you to manually manage this, which often will result in bugs and extra complexity that isn't actually necessary.
Nic Barker recently started a new series on this topic. It's a good resource for this kind of thing. (https://www.youtube.com/watch?v=3rez2rDYHHA)
14
u/skeeto Oct 13 '26 edited Oct 13 '26
There are a couple overflows in the middle of
arena_alloc, very common in arena implementations in any language (including quite a few Rust bump allocators, ex.), making it always UB to run out of memory. It's UB to compute pointers beyond one-past-the-end of an object, and so size checks must not be done using pointers. The relevant lines:First, and less important,
alignmentmight overflow the end of the arena if the user selected a non-power-of-two arena size. Suppose the user makes a 100-byte arena, nearly fills it, and allocates a 8-byte-aligned (i.e. pointer-alignment) object. This places the candidate pointer 4 bytes beyond the end, overflowing the pointer.Second, and the one that always trips, is
out.ptr + size. If the requested object doesn't fit, this is a guaranteed pointer overflow. That is, compilers are allowed to assume this check is always false, and arenas will never run out of memory.Instead compare integer sizes: Compute how much capacity is available and how much space you need, and compare those integer quantities. With unsigned sizes you also need to first check that alignment does not overflow when you add/substract it from either side. With signed sizes (i.e.
ptrdiff_t) you can simply subtract it from available capacity because there's always a negative "runway" available and so no overflow risk.In contrast, computing
size + alignment > capacityrisks an integer overflow.8
u/TheChief275 Oct 14 '26
your macros are so unhygienic it's crazy; makes it seem like you've never programmed in C before.
always wrap macro arguments in parentheses when using them in expressions
1
u/rodrigocfd Oct 13 '26
Isn't
[[nodiscard]]a C++17 feature (and not C)?1
u/GrtflJello Oct 13 '26
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/teleprint-me Oct 13 '26
For the curious, there are many types of allocators. I think the arena is the most popular because its easy to implement and use compared to others, e.g. free list, stack, page, borrow checker, etc.
Its both interesting and educational and makes complex programs easier to implement later on.
For example, I used the arena allocator as a custom interface to manage vulkan allocations. The vulkan interface supports custom allocators when they are aligned with the documented API.
If youre not careful, it can become a bottleneck because it basically becomes a garbage collector if youre not actively freeing memory when you should. The hidden caveat is that the allocator hides the leaks that ASAN would normally warn you about; yes, you should be using a sanitizer!
Kind of a double edged sword, but with diligence, can reduce overall complexity in a project that benefits from it.
1
u/ArmadilloAny6736 Oct 13 '26
In the first code example you do not use the argument len
1
u/gordonmessmer Oct 14 '26
glibc uses memory arenas for performance reasons; their implementation reduces lock contention in threaded applications.
Exposing the arena API to applications can allow them to avoid interleaved allocations of different lifecycles, which can help reduce process resident memory use:
https://gordonmessmer.codeberg.page/dev-blog/2026/03/02/memory-efficiency-with-arena-allocators.html
I hope that's an interesting topic. 😄
1
u/rubidus-api Oct 14 '26
Good thread. A few points raised here match what I ran into while writing an arena for my own C library, so here's how I handled them.
skeeto's overflow. Here is my allocation path, trimmed down to three steps: alignment, padding, and the bounds check. No pointer is formed until the request is known to fit.
Two differences from the code in the article:
ckd_add), so a hugesizereports failure instead of wrapping. skeeto's 100-byte example (offset 97, 8-byte alignment) comes back as out of memory.Provenance. The integer is only used to work out the padding. The pointer the function returns is
a->bufplus an offset, never an integer cast back to a pointer, so it keeps the buffer's provenance and doesn't depend on how a compiler treats integer-to-pointer conversion, which WG14's provenance model (PNVI-ae-udi) is still pinning down.Effective type is the other half. If the backing memory comes from
malloc, it has no declared type, so each object carved out of it takes its effective type from the first store, and that's fine. If the backing is a declared array, like astatic unsigned char buf[N]on a target with no heap, the strict reading of C's effective-type rules (6.5p6-7 in C11) is that the storage keeps its declared type, and accessing anintstored there through anintlvalue is undefined. It's a common pattern, but the standard doesn't bless it. If you want to stay within the letter of the standard, back the arena withmalloc'd memory, or build with-fno-strict-aliasing.WSWhitehouse's grow-in-place idea. My realloc does exactly that: if the block was the most recent allocation, it just moves the offset, with no copy.
Arena first, then a pool. I started with just the arena, which worked great for data that dies together. Then I hit its weak spot: data that gets allocated and freed over and over. Since free is a no-op, the arena keeps growing until the next reset (GrtflJello's point), and it never reuses an address it already handed out (roughly Rabbitical's point). So I added a pool. For the few data types that churn the most, a simple pool on top of the arena should cover it: keep freed items on a stack and hand back the most recently freed one first. The arena still owns the lifetime, and the pool recycles inside it. One rule: the pool's stack lives in the arena too, so a reset takes the pool with it, and you set it up again afterwards.
teleprint-me's ASan caveat is real, and my arena has it too. It doesn't poison memory, so ASan won't catch a use-after-reset. The pool at least fills freed items with 0xDD in debug builds.
And I agree with LeeHide: none of this is free performance, so measure first. For me the main win is lifetime management, not speed.
I picked up this explicit-allocator style from Luca Sas's ACCU 2021 talk Modern C and What We Can Learn From It (the slides call these "temporary allocators").