realloc
realloc(p, n) tries to resize a malloc block to n bytes. It returns a pointer to the (possibly moved) block, or NULL on failure. On failure, p is still valid.
Detailed Explanation
Growing a dynamic array is the job. You pass the old pointer and the new size. The library may extend in place or allocate a new block, copy the old bytes, and free the old block. After a successful move, every pointer into the old block is dangling. Store indices, not interior pointers, if a grow can happen.
The assignment trap is p = realloc(p, n). If realloc fails it returns NULL and leaves the old block allocated. You just overwrote the only pointer to that block with NULL and leaked it. Write:
int *q = realloc(p, n);
if (q == NULL) { /* p still valid */ return -1; }
p = q;
realloc(NULL, n) is malloc(n). realloc(p, 0) is implementation-defined in recent C: it may act like free(p) and return NULL, or return a unique zero-size block. Do not use realloc to free. Call free.
The new tail is uninitialized. Shrinking keeps the prefix. The copy is min(old_size, n) bytes, but you are the one who remembers old_size; the library's copy uses the size it stored internally.
realloc of a pointer that was not from malloc/calloc/realloc, or that was already freed, is undefined behavior. realloc of a stack array is undefined behavior.
A growth strategy that adds one element each time is O(n^2) copies. Double the capacity. Amortized O(1) per push, occasional O(n) pause.
Code Examples
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
int *p = malloc(2 * sizeof *p);
if (p == NULL) {
return 1;
}
p[0] = 1;
p[1] = 2;
int *q = realloc(p, 4 * sizeof *p);
if (q == NULL) {
free(p); /* old block still ours */
return 1;
}
p = q;
p[2] = 3;
p[3] = 4;
printf("%d %d\n", p[1], p[3]); /* prints: 2 4 */
free(p);
return 0;
}Common Gotchas
`p = realloc(p, n)` leaks `p` on failure
use a temporary.
Pointers into the old block dangle after a move
the values were copied; the addresses were not.
`realloc(p, 0)` is a bad `free`
behavior differs across libcs. Call `free(p)`.
Doubling capacity is the usual growth
`+1` each time copies `O(n^2)` elements over the life of the array.