malloc and realloc in C: solved dynamic array exercise

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 realloc when full.

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
#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

1
2
Size: 8 | Capacity: 8
10 20 30 40 50 60 70 80

Common mistakes

  • Overwriting the original pointer with realloc without a temporary pointer.
  • Skipping NULL checks on malloc and realloc.
  • Forgetting final free.

Practical use

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

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.