Reading history

Dynamic Arrays in C With realloc

6 min read 2 views

Build a growable dynamic array in C: size and capacity, safe realloc, doubling growth, arrays of strings, memmove removal and shrinking to fit.

A C array has a fixed size, chosen when you write the program. Real programs often do not know in advance how many items they will need: how many students will enrol, how many lines a file has. The answer is a dynamic array, a block of heap memory that grows with realloc as items are added. This is how Python lists, Java’s ArrayList and C++’s vector work inside. This lesson builds one step by step.

In this lesson you will learn

  • Keeping size and capacity in a struct
  • Growing a block safely with realloc
  • Why doubling the capacity is fast
  • Storing strings in a dynamic array of pointers
  • Removing items with memmove and shrinking to fit

You should know dynamic memory allocation, structures and pointers.

A Growable Array of Integers

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

/* A growable array of ints, like a simple ArrayList or Python list */
typedef struct {
    int *data;
    size_t size;      /* items in use */
    size_t capacity;  /* items allocated */
} IntVec;

void vec_init(IntVec *v) {
    v->data = NULL;
    v->size = 0;
    v->capacity = 0;
}

int vec_push(IntVec *v, int value) {
    if (v->size == v->capacity) {
        size_t new_cap = v->capacity ? v->capacity * 2 : 4;
        int *tmp = realloc(v->data, new_cap * sizeof *tmp);
        if (tmp == NULL)
            return 0;                 /* old block is still valid */
        v->data = tmp;
        v->capacity = new_cap;
        printf("  grew to capacity %zu\n", new_cap);
    }
    v->data[v->size++] = value;
    return 1;
}

void vec_free(IntVec *v) {
    free(v->data);
    vec_init(v);
}

int main(void) {
    IntVec marks;
    vec_init(&marks);

    for (int i = 1; i <= 10; i++)
        if (!vec_push(&marks, i * 7)) {
            puts("out of memory");
            return 1;
        }

    printf("size %zu, capacity %zu\n", marks.size, marks.capacity);
    for (size_t i = 0; i < marks.size; i++)
        printf("%d ", marks.data[i]);
    printf("\n");

    vec_free(&marks);
    printf("after free: size %zu, data %s\n", marks.size, marks.data ? "set" : "NULL");
    return 0;
}

Output

  grew to capacity 4
  grew to capacity 8
  grew to capacity 16
size 10, capacity 16
7 14 21 28 35 42 49 56 63 70 
after free: size 0, data NULL
  • IntVec keeps three things together: a pointer to the items, how many are in use (size) and how many fit in the block (capacity).
  • When size reaches capacity, vec_push asks realloc for a block twice as big. realloc keeps the existing items, moving them to a new place if necessary.
  • The result goes into tmp first. If realloc fails it returns NULL but the old block is still valid. Writing v->data = realloc(v->data, ...) directly would lose the only pointer to it and leak the memory.
  • Calling realloc(NULL, n) behaves like malloc(n), so the very first push needs no special case.
  • Ten pushes needed only three allocations: capacity went 4, 8, 16. Because the capacity doubles, the average cost of each push stays constant, however many items you add.
  • vec_free releases the block and resets the struct, so a dangling pointer is never left behind.

A Dynamic Array of Strings

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

/* Read words into a growing array of strings, then shrink it to fit */
int main(void) {
    const char *input[] = {"Padma", "Meghna", "Jamuna", "Karnaphuli", "Teesta", "Surma"};
    size_t n_input = sizeof input / sizeof input[0];

    char **rivers = NULL;
    size_t size = 0, cap = 0;

    for (size_t i = 0; i < n_input; i++) {
        if (size == cap) {
            size_t new_cap = cap ? cap * 2 : 2;
            char **tmp = realloc(rivers, new_cap * sizeof *tmp);
            if (!tmp) { perror("realloc"); break; }
            rivers = tmp;
            cap = new_cap;
        }
        rivers[size] = malloc(strlen(input[i]) + 1);    /* +1 for '\0' */
        if (!rivers[size]) { perror("malloc"); break; }
        strcpy(rivers[size], input[i]);
        size++;
    }
    printf("stored %zu rivers, capacity %zu\n", size, cap);

    /* remove the item at index 1 by shifting the rest left */
    free(rivers[1]);
    memmove(&rivers[1], &rivers[2], (size - 2) * sizeof *rivers);
    size--;

    /* shrink the block so no space is wasted */
    char **fit = realloc(rivers, size * sizeof *fit);
    if (fit) { rivers = fit; cap = size; }

    printf("after removing one: %zu items, capacity %zu\n", size, cap);
    for (size_t i = 0; i < size; i++)
        printf("  %zu: %s\n", i, rivers[i]);

    for (size_t i = 0; i < size; i++)
        free(rivers[i]);
    free(rivers);
    return 0;
}

Output

stored 6 rivers, capacity 8
after removing one: 5 items, capacity 5
  0: Padma
  1: Jamuna
  2: Karnaphuli
  3: Teesta
  4: Surma
  • Here the array holds char * pointers. Each river name gets its own malloc block of strlen + 1 bytes, the extra byte being for the '\0' terminator.
  • To remove item 1, its string is freed first, then memmove shifts the later pointers one place left. memmove is used instead of memcpy because the source and destination overlap.
  • A final realloc to exactly size items gives back the unused capacity. This is optional, and worth it only when the array will not grow again.
  • Cleaning up takes two stages: free every string, then free the array of pointers.

Fixed Array or Dynamic Array?

Fixed array int a[100]Dynamic array
SizeChosen when you write the codeGrows while the program runs
MemoryStack or static storageHeap
FreeingAutomaticYou must call free
Best forSmall, known sizesUnknown or large amounts of data

Common Mistakes

  1. Assigning realloc‘s result straight back to the only pointer, which leaks the block if it fails.
  2. Growing by one item at a time. Every push may then copy the whole array, making n pushes take about n² steps.
  3. Keeping pointers into the old block after realloc. The data may have moved, so old pointers are invalid.
  4. Forgetting the + 1 for the terminator when copying strings.

Practice Exercises

Exercise 1. Add int vec_pop(IntVec *v, int *out) that removes the last item, stores it in *out and returns 1, or returns 0 if the vector is empty.

Show answer
int vec_pop(IntVec *v, int *out) {
    if (v->size == 0) return 0;
    *out = v->data[--v->size];
    return 1;
}

Exercise 2. Write int vec_insert(IntVec *v, size_t pos, int value) that inserts at position pos, shifting later items right.

Show answer
int vec_insert(IntVec *v, size_t pos, int value) {
    if (pos > v->size) return 0;
    if (!vec_push(v, 0)) return 0;              /* makes room, size grows by 1 */
    memmove(&v->data[pos + 1], &v->data[pos],
            (v->size - 1 - pos) * sizeof v->data[0]);
    v->data[pos] = value;
    return 1;
}

Frequently Asked Questions

Why double the capacity instead of adding a fixed amount?

With doubling, the total copying work over n pushes is less than 2n, so each push costs a constant amount on average. Adding a fixed amount, such as 10 more each time, makes the total copying grow with n², which becomes very slow for large arrays.

Does realloc always move the data?

No. If there is free space right after the current block, realloc may simply extend it. You cannot know which will happen, so always use the pointer it returns.

Summary

  • A dynamic array stores a pointer, a size and a capacity.
  • Grow it with realloc into a temporary pointer, doubling the capacity.
  • Use memmove to shift overlapping items when inserting or removing.
  • Free every inner allocation, then the array itself.

Next: Dynamic 2D Arrays in C.

Lessons are also marked complete when you click Next.

Leave a Reply

Your email address will not be published. Required fields are marked *