Codiqo

Learn C · lesson 42 of 60 · about 8 minutes

Growing Arrays with realloc

Collect the open ports: make a dynamic array bigger as items arrive, by doubling its capacity with realloc.

What you'll learn

  • Resize memory with realloc
  • Track size and capacity
  • Use the doubling strategy

The open ports

Next the admin types the machine's open ports, one number after another until 0. This time nobody says how many are coming, so the report can't ask for the right amount up front. It starts with room for 2 ports, and whenever the array is full it asks realloc for twice as much, printing Room for 4 ports so the admin can see it grow. At the end it lists the ports, or says there are none, and frees the array.

Size and capacity

A growing array tracks two numbers:

  • count: how many items are in use
  • capacity: how many items fit before it must grow

When count reaches capacity, realloc(ptr, new_bytes) gives you a bigger block, copying the old items across. Doubling the capacity each time keeps resizing rare.

Reading numbers until the input ends

#include <stdio.h>
#include <stdlib.h>

int main(void) {
    int count = 0;
    int capacity = 2;
    int *nums = malloc(capacity * sizeof *nums);
    if (nums == NULL) return 1;

    int value;
    while (scanf("%d", &value) == 1) {
        if (count == capacity) {
            capacity *= 2;
            int *bigger = realloc(nums, capacity * sizeof *nums);
            if (bigger == NULL) {
                free(nums);
                return 1;
            }
            nums = bigger;
            printf("(grew to %d)\n", capacity);
        }
        nums[count++] = value;
    }
    printf("Read %d numbers, last %d\n", count, nums[count - 1]);
    free(nums);
    return 0;
}

Output

(grew to 4)
(grew to 8)
Read 5 numbers, last 23

Tip

Store realloc's result in a new variable first. If it fails it returns NULL, and writing that straight into nums would lose your only pointer to the old block.

Why double?

Each realloc may have to copy every item to a new place, so you want as few as possible. Growing by one slot at a time means a realloc for every new item. Doubling means the array gets bigger faster than the items arrive: to reach room for 1000 items, it only grows 10 times.

Counting the reallocs

#include <stdio.h>

int main(void) {
    int doubling = 0;
    int by_one = 0;
    for (int cap = 1; cap < 1000; cap *= 2) doubling++;
    for (int cap = 1; cap < 1000; cap++) by_one++;
    printf("Doubling: %d reallocs, one at a time: %d\n", doubling, by_one);
    return 0;
}

Output

Doubling: 10 reallocs, one at a time: 999

Now try it yourself

This lesson is free in Codiqo, with 9 questions on what you just read. You can only learn to code by writing code, so it ends with a short program you write yourself, which we run and check straight away.