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
#include <stdio.h>
#include <stdlib.h>
int main(void) {
size_t cap = 4;
size_t n = 0;
int *v = malloc(cap * sizeof(int));
if (!v) return 1;
for (int x = 10; x <= 80; x += 10) {
if (n == cap) {
cap *= 2;
int *tmp = realloc(v, cap * sizeof(int));
if (!tmp) {
free(v);
return 1;
}
v = tmp;
}
v[n++] = x;
}
printf("Size: %zu | Capacity: %zu\n", n, cap);
for (size_t i = 0; i < n; i++) printf("%d ", v[i]);
printf("\n");
free(v);
return 0;
}Expected output
Size: 8 | Capacity: 8
10 20 30 40 50 60 70 80Common 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.