Course contentsShow
← C
Lesson 984 of 1,21914. Data Structures in CFree lesson

Geometric resizing with realloc

Geometric resizing with realloc

What you'll learn: How to efficiently grow a dynamic array by doubling its size rather than adding space one element at a time.

The problem with being "just big enough"

When using realloc, it is tempting to increase your array size by exactly one element every time you need more space. However, realloc is an expensive operation. It often has to find a completely new, larger spot in memory and copy all your existing data there. If you add 1,000 items one by one, you might perform 1,000 copies, which makes your program incredibly slow.

The "Suitecase" analogy

Imagine you are packing for a trip. If you buy one souvenir, you buy a slightly larger suitcase and move everything. Then you buy another souvenir and repeat the process. You’d spend your whole vacation moving clothes!

Instead, we use geometric resizing. When the "suitcase" is full, we double its size. This gives us plenty of "breathing room" for future items. Even though we waste a little memory, we save a massive amount of time because we only have to move our belongings a few times.

Implementing the double-up strategy

To do this, we track two values: the size (how many items are currently inside) and the capacity (how many items the memory can actually hold).

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

int main() {
    int capacity = 2; // Start small
    int size = 0;
    int *arr = malloc(capacity * sizeof(int));

    for (int i = 0; i < 10; i++) {
        // Check if we are out of room
        if (size == capacity) {
            capacity *= 2; // Double the capacity
            int *temp = realloc(arr, capacity * sizeof(int));
            
            if (temp == NULL) {
                free(arr);
                return 1; // Memory allocation failed
            }
            arr = temp;
            printf("Resized to %d\n", capacity);
        }

        arr[size] = i;
        size++;
    }

    free(arr);
    return 0;
}

Why this works

By doubling the capacity, we ensure that as the array gets bigger, the frequency of reallocations gets lower. Adding 1,000 elements only requires about 10 reallocations (2, 4, 8, 16... up to 1024) instead of 1,000. This is the standard way professional data structures, like C++ Vectors or Python Lists, handle growth.

Key takeaway

Always resize dynamic arrays by a growth factor (usually 2x) to minimize expensive memory copies.