Dynamic buffer in C: solved exercise
Dynamic buffer in C: solved exercise
If you searched for a solved dynamic buffer in C, here is the classic dynamic array pattern: initial malloc, realloc when capacity is exhausted, and free at the end. The doubling strategy guarantees that the amortized insertion cost is O(1).
This pattern is the foundation of structures like std::vector in C++ or ArrayList in Java, implemented manually in C.
Problem statement
Implement a dynamic integer array with:
buf_create(initial_cap): creates the buffer.buf_append(b, val): adds an element, doubling capacity if needed.buf_print(b): displays all elements.buf_free(b): releases the memory.
Add the integers from 1 to 10 starting with an initial capacity of 2 to force several realloc calls.
C solution
Expected output
Common mistakes
- Assigning the result of
reallocdirectly tob->data: ifreallocreturnsNULL, the original pointer is lost and cannot be freed, causing a memory leak. Always use a temporary variabletmp. - Not freeing
b->databefore freeingb:free(b)only frees the container struct, not the internal array. - Not checking the return value of
mallocorrealloc: dereferencing aNULLpointer is undefined behavior. - Using a growth factor of 1 (adding only one slot of capacity): leads to O(n²) total insertion time because every insertion triggers a
realloc.
Practical use
The dynamic array is the most widely used data structure in practice: reading lines of variable length, storing query results whose size is not known in advance, implementing variable-size stacks and queues, and as the basic building block of parsers and compilers.
Recommended next exercise
- Calloc in C: solved exercise
- Pointer to struct in C: solved exercise
- Linked list in C: solved exercise
- All C exercises
Guided practice and full book
If you want a complete path with progressive difficulty:
FAQ
Why double the capacity instead of increasing it by a fixed amount?
With a fixed increment of k, inserting n elements requires n/k calls to realloc, each copying all previous elements. The total cost is O(n²/k) = O(n²). With doubling, only log₂(n) calls are needed and the amortized cost per insertion is O(1), with total cost O(n).
What happens if realloc cannot find contiguous memory?
realloc may move the block to a different memory region: it copies the data, frees the original block, and returns the new pointer. If no memory is available, it returns NULL and the original block remains intact. That is why a temporary variable must be used before reassigning.
When should calloc be used instead of malloc for the buffer?
Use calloc if you need to guarantee that elements are initialized to zero (for example, to detect unwritten values or for compatibility with code that assumes zeros). For an array where all elements will be written before being read, malloc is sufficient and slightly faster.