Malloc and free in C: solved dynamic memory exercise

  2 minutes

If you searched for malloc and free in C solved exercises, this example covers allocation, resize, and cleanup safely.

Allocate an integer array dynamically, fill it, resize with realloc, print values, and free memory.

#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;
}
10 20 30 40 50
  • Not checking malloc/realloc return value.
  • Overwriting original pointer directly on realloc.
  • Double-free or missing final free.

Dynamic memory is essential in stream processing, variable-size buffers, and adaptive data structures.

If you want a complete path with progressive difficulty:

Yes. It targets patterns that commonly appear in practice assignments, technical interviews, and C programming exams.

In Programming in C in 100 Solved Exercises and C Exercises. Kindle Unlimited: View on Amazon.

Start with small inputs, run edge cases (empty, one item, max capacity), then rewrite the solution from scratch without copying.