Growing a buffer in C
Doubling on demand, and never assigning realloc's result over your only pointer.
#include <stdlib.h>
int push(int **values, size_t *len, size_t *cap, int value) {
if (*len == *cap) {
size_t bigger = (*cap == 0) ? 4 : *cap * 2;
int *grown = realloc(*values, bigger * sizeof(int));
if (grown == NULL) {
return 0;
}
*values = grown;
*cap = bigger;
}
(*values)[*len] = value;
(*len)++;
return 1;
}
How it works
- Growth by doubling keeps the amortised cost constant.
- If
reallocfails it returns NULL and the old block survives. - So assign to a temporary and only then replace the pointer.
Keywords and builtins used here
NULLifintpushreturnsize_tsizeof
The run, in numbers
- Lines
- 16
- Characters to type
- 313
- Tokens
- 113
- Three-star pace
- 95 tpm
At the three-star pace of 95 tokens a minute, this run takes about 71 seconds.
Step 4 of 5 in Dynamic memory, step 13 of 25 in Pointers & memory.