realloc in C
Resizing a heap allocation, growing an array.
#include <stdlib.h>
int *grow(int *items, int old_n, int new_n) {
int *bigger = realloc(items, new_n * sizeof(int));
if (bigger == NULL) {
free(items);
return NULL;
}
for (int i = old_n; i < new_n; i++)
bigger[i] = 0;
return bigger;
}
How it works
reallocreturns a possibly-moved larger block.- On failure the old block is freed to avoid a leak.
- New slots are zeroed before use.
Keywords and builtins used here
NULLforgrowifintreturnsizeof
The run, in numbers
- Lines
- 12
- Characters to type
- 235
- Tokens
- 77
- Three-star pace
- 95 tpm
At the three-star pace of 95 tokens a minute, this run takes about 49 seconds.
Step 3 of 5 in Dynamic memory, step 12 of 25 in Pointers & memory.