malloc and realloc in C: solved dynamic array exercise

  2 minutes

If you searched for malloc and realloc in C solved exercise, this is a practical dynamic array pattern with capacity growth.

Implement a dynamic integer array in C that:

  • starts with capacity 4,
  • inserts 8 values,
  • doubles capacity using realloc when full.
#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;
}
Size: 8 | Capacity: 8
10 20 30 40 50 60 70 80
  • Overwriting the original pointer with realloc without a temporary pointer.
  • Skipping NULL checks on malloc and realloc.
  • Forgetting final free.

This pattern appears in dynamic lists, buffers, and runtime-sized data structures.

If you want a complete path with progressive difficulty:

When you need to resize already allocated memory without manual block-by-block copying.

It is risky. Use a temporary pointer to avoid losing the original allocation on failure.

Doubling capacity is a common and efficient approach for repeated append operations.