Kodewick
Start learning →
Arrays that grow: realloc6 / 50

Arrays that grow: realloc

Lesson 6 of 50 · Part 2 · Arrays and linked lists · about 14 minutes

A dynamic array lives on the heap: start with malloc, and when it's full realloc a block twice as big, catching the result in a temporary pointer because the data may move; doubling makes each push O(1) amortized.

The last lesson's array list holds at most MAX elements; once full, nothing more goes in. Real programs don't know in advance how much they'll hold. The fix is to put the array on the heap: malloc a small block, and when it fills up, realloc a bigger one. Python's list and C++'s vector work this way underneath.

A block on the heap

Once the array lives on the heap, the struct no longer holds the array itself: just a pointer to the block on the heap, plus two numbers:

1typedef struct {2    int *data;      // points at a block on the heap3    int len;        // how many are in it4    int cap;        // how many the block can hold5} Vec;

len is how many slots are in use, cap how many there are. len == cap means full.

Start by asking malloc for a block, say room for 4 ints: v.data = malloc(4 * sizeof(int));. Now cap = 4 and len = 0. malloc counts in bytes, which is why you multiply by sizeof(int). A block on the heap doesn’t vanish when a function returns: when you’re done with it, give it back with free(v.data).

stack

v.dataint *
v.lenint2
v.capint4

heap

7 8 _ _int[4]
v itself is on the stack, just a pointer and two numbers; the data is in its block on the heap: 2 in use, 2 still free
Choose one

v.data = malloc(4 * sizeof(int)); An int takes 4 bytes. How many bytes does this line ask the heap for?

Guess the outputA wrong guess is fine

What does this program print?

1#include <stdio.h>2#include <stdlib.h>3 4int main(void) {5    int *data = malloc(4 * sizeof(int));6    int len = 0, cap = 4;7    for (int i = 1; i <= 3; i++)8        data[len++] = i * 10;9    printf("%d %d %d\n", len, cap, data[len - 1]);10    free(data);11    return 0;12}

Full: get a block twice as big

realloc(p, new_size) gives you memory of the new size with the old contents copied in. If the block can't grow where it is, it moves to a new address and the old block is given back for you.

stack

v.dataint *

heap

7 8int[2]
7 8 _ _int[4]

When realloc can't grow in place: a new block, the data copied over, the old block given back, the pointer moved

So after a realloc, any old address you kept is no good: only the new pointer it returns counts.

main.c
1#include <stdio.h>2#include <stdlib.h>3 4typedef struct {5    int *data;6    int len;7    int cap;8} Vec;9 10int push(Vec *v, int x) {11    if (v->len == v->cap) {12        int cap = v->cap ? v->cap * 2 : 1;       // double every time13        int *bigger = realloc(v->data, cap * sizeof(int));14        if (bigger == NULL) return 0;            // no memory: the old block is still there15        printf("  new block: room for %d -> %d\n", v->cap, cap);16        v->data = bigger;17        v->cap = cap;18    }19    v->data[v->len++] = x;20    return 1;21}22 23int main(void) {24    Vec v = {NULL, 0, 0};25    for (int i = 1; i <= 10; i++)26        push(&v, i * 10);27    printf("len = %d, cap = %d, last = %d\n", v.len, v.cap, v.data[v.len - 1]);28    free(v.data);29    return 0;30}
Output
  new block: room for 0 -> 1
  new block: room for 1 -> 2
  new block: room for 2 -> 4
  new block: room for 4 -> 8
  new block: room for 8 -> 16
len = 10, cap = 16, last = 100

realloc(NULL, size) is the same as malloc(size), so starting with data as NULL is fine.

Choose one

Starting from cap = 0 (the first block has 1 slot) and doubling every time it fills up, what is cap after 20 pushes?

Choose one

You save int *old = v.data;, then a push makes realloc move to a new address. What about old now?

Don't write p = realloc(p, …)

When realloc can't get the memory it returns NULL, and the old block is still there. Write v->data = realloc(v->data, …) and a failure leaves v->data as NULL: the old block can't be found again, the data is lost and the memory leaks. So catch it in a temporary pointer, bigger, and only use it once it isn't NULL.

stack

v.dataint *
biggerint *?

heap

3 1 4 1int[4]

The same failed realloc, written two ways: caught in bigger, the data is safe; assigned straight back to v.data, the old block is lost
Choose one

When realloc can’t get the memory and returns NULL, what happens to the old block?

Choose one

realloc can fail. Which of these is right?

Exercise 1

Write push

Finish push: when full, realloc to twice the size (starting at 1), catching the result in a temporary pointer first. Make the program print len = 5, cap = 8.

It should print
len = 5, cap = 8
exercise1.c
1#include <stdio.h>2#include <stdlib.h>3 4typedef struct {5    int *data;6    int len;7    int cap;8} Vec;9 10int push(Vec *v, int x) {11    if (v->len == v->cap) {12        int cap = v->cap ? v->cap * 2 : 1;13        // realloc to cap ints: catch it, check it, switch to it14    }15    v->data[v->len++] = x;16    return 1;17}18 19int main(void) {20    Vec v = {NULL, 0, 0};21    for (int i = 1; i <= 5; i++)22        push(&v, i);23    printf("len = %d, cap = %d\n", v.len, v.cap);24    free(v.data);25    return 0;26}
Output
Press Run or Ctrl+Enter

Why doubling

Doubling from 1 slot to 32: each row is the new block, amber the elements copied from the old one, green the room left for the next pushes; on the right, how many were copied that time and in total. 32 pushes take 31 copies; growing one slot at a time would take 496
When full, grow byCopies to put n inPer push on average
one slotabout n²/2O(n)
doublingfewer than nO(1) (amortized)

The price of doubling is some empty slots (at most half). A little space for a lot of time: the choice most languages' dynamic arrays make.

Guess the outputA wrong guess is fine

Starting with 1 slot and doubling, how many copies does it take to put 16 numbers in?

1#include <stdio.h>2 3int main(void) {4    int cap = 1, copies = 0;5    for (int len = 0; len < 16; len++) {6        if (len == cap) {7            copies += len;   // a new block: the len elements so far are copied over8            cap *= 2;9        }10    }11    printf("%d\n", copies);12    return 0;13}
Choose one

What if, when full, you only added 10 slots (cap += 10)? Pushing n values, what does each push cost on average?

Choose one

Start at 1 slot, double every time it fills up, and push 17 values in all. What is cap now, and how many slots are empty?

Exercise 2

Count the copies

Starting with 1 slot and doubling, put 100 numbers in. Finish the counting and print how many copies it took.

It should print
127
exercise2.c
1#include <stdio.h>2 3int main(void) {4    int cap = 1, copies = 0;5    for (int len = 0; len < 100; len++) {6        // full (len == cap): copy len elements, double cap7    }8    printf("%d\n", copies);9    return 0;10}
Output
Press Run or Ctrl+Enter

Summary

Take-away

A dynamic array: when full, realloc to double

  • len is the slots in use, cap the slots there are
  • realloc may move: only the pointer it returns counts
  • Catch it in a temporary pointer: on failure the old block is still there
  • Doubling: each push is O(1) amortized
1int *bigger = realloc(v->data, cap * 2 * sizeof(int));2if (bigger == NULL) return 0;3v->data = bigger;4v->cap *= 2;