C Programming: Memory, Pointers and the Stack · Dynamic Memory

Growing Arrays with realloc

Start small, and when the array is full, double its capacity with realloc. This is how dynamic arrays grow.

realloc_array.c

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

int main(void) {
    int capacity = 2;
    int size = 0;
    int *items = malloc(capacity * sizeof(int));
    for (int v = 5; v <= 20; v += 5) {
        if (size == capacity) {
            capacity *= 2;
            items = realloc(items, capacity * sizeof(int));   /* grow the block */
        }
        items[size] = v;
        size++;
    }
    printf("size=%d capacity=%d last=%d\n", size, capacity, items[size - 1]);
    free(items);
    return 0;
}

Step by step

  1. capacity is created on the stack with the value 2.
  2. size is created on the stack with the value 0.
  3. Room for 2 ints.
  4. v is created on the stack with the value 5.
  5. C checks size == capacity to decide which way the code goes.
  6. In the int[2] that items points to, index 0 changes from ? to 5.
  7. size changes from 0 to 1.
  8. v changes from 5 to 10.
  9. C checks size == capacity to decide which way the code goes.
  10. In the int[2] that items points to, index 1 changes from ? to 10.
  11. size changes from 1 to 2.
  12. v changes from 10 to 15.
  13. C checks size == capacity to decide which way the code goes.
  14. Full (size == capacity): double to 4.
  15. The block grows to 4 ints; 5 and 10 are kept.
  16. In the int[4] that items points to, index 2 changes from ? to 15.
  17. size changes from 2 to 3.
  18. v changes from 15 to 20.
  19. C checks size == capacity to decide which way the code goes.
  20. In the int[4] that items points to, index 3 changes from ? to 20.
  21. size changes from 3 to 4.
  22. v goes out of scope and disappears.
  23. It prints size=4 capacity=4 last=20.
  24. items changes from [5, 10, 15, 20] to → freed memory (dangling).
  25. The method returns 0.
  26. size 4, capacity 4, last 20.