Malloc and free in C: solved exercise
If you searched for malloc and free in C solved exercises, this example covers allocation, resize, and cleanup safely.
Problem statement
Allocate an integer array dynamically, fill it, resize with realloc, print values, and free memory.
C solution
#include <stdio.h>
#include <stdlib.h>
int main(void) {
int n = 3;
int *a = malloc(n * sizeof(int));
if (a == NULL) {
fprintf(stderr, "Allocation error\n");
return 1;
}
for (int i = 0; i < n; i++) a[i] = (i + 1) * 10;
int new_n = 5;
int *tmp = realloc(a, new_n * sizeof(int));
if (tmp == NULL) {
free(a);
fprintf(stderr, "Resize error\n");
return 1;
}
a = tmp;
for (int i = n; i < new_n; i++) a[i] = (i + 1) * 10;
for (int i = 0; i < new_n; i++) printf("%d ", a[i]);
printf("\n");
free(a);
return 0;
}Expected output
10 20 30 40 50Common mistakes
- Not checking
malloc/reallocreturn value. - Overwriting original pointer directly on
realloc. - Double-free or missing final
free.
Practical use
Dynamic memory is essential in stream processing, variable-size buffers, and adaptive data structures.
Recommended next exercise
- Pointer to pointer in C: solved exercise with reference update
- Pointers in C: solved pass-by-reference exercises
- Binary tree in C: solved insertion and search exercise
- All C exercises
Guided practice and full book
If you want a complete path with progressive difficulty:
FAQ
Is this exercise useful for C exams and technical interviews?
Yes. It targets patterns that commonly appear in practice assignments, technical interviews, and C programming exams.
Where can I keep practicing with more solved C exercises?
In Programming in C in 100 Solved Exercises and C Exercises. Kindle Unlimited: View on Amazon.
How should I practice this exercise type to improve faster?
Start with small inputs, run edge cases (empty, one item, max capacity), then rewrite the solution from scratch without copying.