C/C++ Arena

Step 5 of 9

Growing with realloc

realloc(p, new_size) resizes a heap block, keeping the old contents. It may move the block, so always use the pointer it returns:

int *tmp = realloc(a, new_cap * sizeof(int));
if (tmp == NULL) { /* a is still valid */ }
a = tmp;

Growing by doubling the capacity keeps it fast even for many pushes.

Your turn: read integers until the end of input (you don't know how many!) into a heap array that starts with capacity 2 and doubles when full. Print how many you read, the capacity at the end, and the last number:

Input 5 6 7 8 9 prints count 5 cap 8 last 9.

Previous: calloc and strdup-style copies Next: Memory bugs to avoid