r/C_Programming • u/pjl1967 • May 20 '26
My own bare-bones dynamic array
About a month ago, somebody posted asking for design advice for a dynamic array. My then advice was to treat the element type as an opaque type T.
I've had my own implementation of such a dynamic array lying around for a while, but finally had a use for it, so I gave it a bit of polish and it's here:
If you wanted it to be even more bare-bones, you could keep only the regular (bounds-checking) functions or the no-check (_nc) functions, whichever you prefer.
10
Upvotes
View all comments
Show parent comment
2
u/pjl1967 May 22 '26
From the user's perspective,
array_reserve()does not depend on the current length.At least in my use-cases, I never care what the current length is. All I know is that I want to reserve space for N more elements. That does not require me to know what the current length is.
It didn't have to. It could have bumped the capacity by simply doubling the current length. However, powers of two play much nicer with many memory allocators that tend to round up anyway. If you use non-powers-of-two, the block of memory you get will actually be larger than what you think you have, so you end up wasting memory.
For example, suppose you request a 152-byte chunk and
reallocdoesn't have a 152-byte chunk, so it gives you a 256-byte chunk.capwould say there's only room for 152 bytes (divided by whatever the element size is), but the actual chunk that you already have is 256 bytes, so you're wasting your own memory.The other problem with simply doubling the current length is that the slope of the capacity curve can increase much faster thus wasting more memory. Using the least power of two makes the slope much more gentle thus reducing memory waste while still nicely amortizing reallocation.
At this point,
ahas space reserved for 1024ints, so it already does exactly your use-case.