A generic dynamic array in C that stores no capacity and needs no struct

12 points by alurm


olliej

[edit: I forgot the most obvious problem: this has the same problem as arrays vs pointers in C++, IntVec tells you you’re looking at an array but a pointer type doesn’t tell you if you an array or a pointer]

There seems to be an assumption that realloc grows at power of two rates, which is probably true on the whole, but I really wish people would simply stop using realloc: it wastes space if you don’t need, if you don’t grow at the correct rate you end up with unnecessary copies (in addition to excessive memory use).

There are APIs you can use to get the appropriate allocation size for a given requested capacity, and then use that as your internal buffer capacity. That gives you guaranteed minimum wastage and copying.

Now I think the reason this particular allocator uses 2^n allocation sizes specifically to allow it to go directly from current element count to capacity, but of course you can do via the above allocation size APIs - though the overhead of that call might matter enough for their use cases.