Post 2 of the Dynamic Arrays in C series · Full source code
Where We Left Off
In Post 1 we built an array that does three things: allocate a fixed buffer, push integers into it, and free everything when we're done. It works, until it doesn't. The moment the user pushes one element more than the initial capacity allows, array_push returns -1 and refuses to cooperate. The array is full and there's nothing we can do about it.
That's not a dynamic array. It's a fixed-size buffer with a nice API around it. A real dynamic array solves the fundamental problem: the user doesn't know how many elements they'll need. Maybe it's 5, maybe 5 million. The array should handle either case without the caller worrying about capacity.
The mechanism that makes this possible is realloc. It's one function call, one line of code, and the single most misunderstood function in the C standard library. Most C programmers know what it does in the abstract, "it resizes an allocation." Fewer understand the two distinct things it can do under the hood, why that distinction matters for correctness, and why writing arr->data = realloc(arr->data, new_size) is a bug waiting to happen.






