Arrays that grow: realloc
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.lenint2v.capint4heap
v.data = malloc(4 * sizeof(int)); An int takes 4 bytes. How many bytes does this line ask the heap for?
sizeof(int) and you get only 4 bytes, room for a single int, and writing further goes out of bounds. It is a very common mistake.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}
data[len++] = x puts x in data[len] and then adds 1 to len, so the last one is in data[2]: 30.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
So after a realloc, any old address you kept is no good: only the new pointer it returns counts.
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}
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.
Starting from cap = 0 (the first block has 1 slot) and doubling every time it fills up, what is cap after 20 pushes?
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
When realloc can’t get the memory and returns NULL, what happens to the old block?
realloc can fail. Which of these is right?
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.
len = 5, cap = 8
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}
Why doubling
| When full, grow by | Copies to put n in | Per push on average |
|---|---|---|
| one slot | about n²/2 | O(n) |
| doubling | fewer than n | O(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.
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}
What if, when full, you only added 10 slots (cap += 10)? Pushing n values, what does each push cost on average?
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?
Count the copies
✓Starting with 1 slot and doubling, put 100 numbers in. Finish the counting and print how many copies it took.
127
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}
Summary
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;