Lesson 23: calloc, realloc & dynamic arrays
Last lesson we met malloc — which allocates a block but leaves garbage in it. calloc(n, size) goes one step further: it allocates AND zeroes every byte. realloc(p, new_size) resizes an existing block — growing or shrinking it — but beware: it may move the block to a new address, so always store the
realloc is like moving to a bigger storage unit: the moving company may relocate all your belongings to a new unit somewhere else and hand you a new key. Never throw away the old key before the new one is in your hand — otherwise, if the move fails, you've lost the old unit too.
- calloc(n, size)
- Allocates a block for n elements of size bytes each — and also zeroes every byte.
- realloc(p, new_size)
- Resizes an existing block. The values are preserved, but the block may move to a new address.
- temporary pointer (tmp)
- The safe pattern: int *tmp = realloc(arr, ...); and only if tmp isn't NULL — arr = tmp;. This way the original block isn't lost on failure.
- capacity
- How many elements the block can hold. In a dynamic array, when capacity runs out — the convention is to double it with realloc.
- dynamic array
- A heap array whose size is set at runtime and can grow on demand — unlike a regular fixed-size array.