malloc and realloc in C: solved dynamic array exercise
malloc and realloc in C: solved exercise
If you searched for malloc and realloc in C solved exercise, this is a practical dynamic array pattern with capacity growth.
Problem statement
Implement a dynamic integer array in C that:
- starts with capacity 4,
- inserts 8 values,
- doubles capacity using
reallocwhen full.
C solution
Expected output
Common mistakes
- Overwriting the original pointer with
reallocwithout a temporary pointer. - Skipping
NULLchecks onmallocandrealloc. - Forgetting final
free.
Practical use
This pattern appears in dynamic lists, buffers, and runtime-sized data structures.
Recommended next exercise
Guided practice and full book
If you want a complete path with progressive difficulty:
FAQ
When should I use realloc in C?
When you need to resize already allocated memory without manual block-by-block copying.
Is v = realloc(v, ...) safe?
It is risky. Use a temporary pointer to avoid losing the original allocation on failure.
What growth strategy is practical?
Doubling capacity is a common and efficient approach for repeated append operations.