Malloc and free in C: solved dynamic memory exercise

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

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
#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

1
10 20 30 40 50

Common mistakes

  • Not checking malloc/realloc return 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.

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.