r/cprogramming • u/Ok_Firefighter_2454 • Aug 20 '26
Code Review: Custom Memory Allocators (Arena, Double-Ended Stack)
https://github.com/Ash4dev/mem-allocI am a self-taught programmer (<1 yr, non-CS MS grad) intending to break-in on systems programming roles. I've been reading on CS fundamentals: computer organization and architecture and operating systems.
I used Ginger Bill's awesome blogs as a starting point to understand and work on some of the many memory allocation strategies.
I've reached a point where I think external feedback is critical to proceed ahead on this project.
Community: Pls review my project and suggest any improvements that can be beneficial.
P.S. I intend to list it on my resume. I'm also having a hard-time deciding what points should go on it and not. Any help here would go a really long way. (Bonus)
2
u/flyingron Aug 20 '26
You might want to lookup max_align_t in stddef.h
2
u/WittyStick Aug 20 '26 edited Aug 21 '26
I'm not sure why you feel the need to comment all of the parameter names in the header. Just because you can omit the parameter name, doesn't mean you must. The parameter names are helpful for tooling such as auto-complete - leave them in there.
You should probably make your types
Arena_Allocator/DES_Allocator, etc into opaque pointers - declare them in the header but define them in the .c file. The header doesn't need a definition because all of your functions take or return a pointer argument, so they be can declared with an incomplete type. The user of the API shouldn't be able to access their fields directly, because they will, and will end up with broken code if you change the types.Your
is_power_of_2andforward_aligncan be written more efficiently, avoiding unnecessary branching.is_power_of_2ispopcount(x) == 1. (popcntis available on most hardware). If you use__builtin_popcountllit will use a fallback on CPUs without a popcount instruction. If using C23, there'sstdc_has_single_bitfrom<stdbit.h>.forward_aligncan usestdc_bit_ceilalso. If using a glibc which doesn't have<stdbit.h>you can use__builtin_stdc_{has_single_bit,bit_ceil}from GCC. For compilers not using GNUC, there's equivalent functionality available -bit_ceilis usually implemented withlzcntand a1 <<.initialize_arenalooks good. Doesn't leak memory on failure.destroy_arenahas potential issues. Passing a NULL pointer will silently ignore any issues rather than raising an obvious error, which may lead to memory leaks. Also, since you are passing a pointer to a pointer, the pointer may be non-null and pass this test, but it may point to a null pointer, in which case you'll have a null pointer dereference since you aren't checking that.allocate_alignedhas potential issues with unsigned wrapping due to modular arithmetic. If caller passes in some largealignmentorsize(or uses a negative signed value implicitly cast to unsigned), your calculations could cause a value to exceedSIZE_MAX, and result in something smaller than you expect. You can't really test againstSIZE_MAXhere because it is generally always true. The recommendation would be to have a maximum which is at least less thanSIZE_MAX >> 1(akaRSIZE_MAX) and ensure any addition results in a value<= RSIZE_MAX. This resolves the issue because any negative signed integer which is cast to an unsigned integer would result in a number > RSIZE_MAX, as would any large unsigned integer that could cause wrapping to a small number. There are some that argue you should use signed integers - but this doesn't solve the issues any better - it just results in UB, because signed overflow is UB. Sizes should be unsigned.Not really looked in depth, but just some thoughts based on skimming through your code.
2
u/Honest_Medium_2872 Aug 25 '26
Some thoughts:
The distinction between
allocate_alignedandallocateis rather superfluous. It makes sense in the back, but for consuming the api it becomes a chore to track alignment. The best strategy is as followed: oneallocatefunction. This allows you to always callallocateno matter what, the underlying implementation ofallocatecan determine what allocation strategy to use (aligned vs unaligned). This opens the door to allowing you to properly pad requests transparently to the caller.In the context of an Arena, the allocated memory's size only needs to be at least the size of the request, this means you can prepend a header to the allocation and append a pad. The next best approach is to use a separate arena for the unaligned type - i tend to avoid these because managing multiple arenas for different types becomes cognitive overload.
This pattern extends to your realloc, calloc, etc implementations.
Your heap marker structs should be implementation specific, therefore move it to your .c file or a private header. Same thing with your alignment macro, your Arena definition (the struct), the buf_t and your util functions (is_pow_2, align_forward, etc).
Use uint8_t from
stdint.has your byte typeYour initialize function is good. Some pedantic commentary as follows:
How I would rewwrite this function:
allocate_alignedis proper, but some more pedantic commentary on the code:How I would rewrite this function:
If I understand what you are trying to do with
arena_markerthen you can just take a copy of yourArenastruct. It doesn't need to be a deep copy (where you copy the underlying arena bytes) just a shallow copy of the Arena struct itself.This is because everything in your arena struct is just scalar values - no fixed size arrays. Pointers are scalar because they just hold a numeric address to data, not the underlying vector.
Your arena definition could be much simpler:
This makes your
allocmuch simpler:If you plan to support multiple sizes in the arena, the logic becomes more complex. A good way to handle this is using an object header struct like:
This gets prepended to every allocation implicitly by the allocator, it is transparent to the caller but allows your allocator to track chunks of memory.
Working off the proposed refactor: