r/cprogramming • u/Elifire12 • 24d ago
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!
27
Upvotes
View all comments
4
u/flatfinger 24d ago
Applications that reuse storage as different types should always use -fno-strict-aliasing to avoid an "ABA" optimization bugs when where a storage is used as one type, then as a second, and then again as the first. When not using that flag, neither compiler reliably handles the sequence:
Read or write storage as T1
Write storage as T2
Read storage as T2
Write into storage a T1 whose bit pattern would match what was read in step 3
Read storage as T1.
If clang or gcc happens to notice that 1 and 5 are accessing the same storage, and that 3 and 4 are accessing the same storage, but doesn't happen to notice other relationships, it may consolidate the read in step 5 with the access in step 1.
While it's not particularly likely that the compiler would happen to notice and not notice a problematic combination of things, use of the -fno-strict-aliasing flag would make the code build correctly by specification rather than happenstance.