Pointers & Memory · intermediate · ~12 min
Resize owned storage while preserving the original allocation on failure.
realloc can resize an existing allocation and may move it. The central skill is handling both outcomes: success replaces the old allocation, while failure for a nonzero request leaves the old allocation valid. Keep the owner until you know which outcome occurred.
For a nonzero new size, assign the realloc result to a temporary. If it is NULL, report failure and keep the original owner. On success adopt the returned pointer and stop using all pointers into the old allocation, even if the numeric address appears unchanged.
The first min(old size, new size) bytes are preserved. Newly added bytes are not initialized. Check addition and multiplication before calculating an allocation size.
Handle a request for size zero explicitly with free and a documented empty-state result. This avoids relying on realloc(p, 0), whose rules vary across C versions and implementations.
realloc can resize an existing allocation and may move it. The central skill is handling both outcomes: success replaces the old allocation, while failure for a nonzero request leaves the old allocation valid. Keep the owner until you know which outcome occurred.
#include <stdio.h>
#include <stdlib.h>
int main(void) {
int *p = malloc(2 * sizeof *p);
if (p == NULL) return 1;
p[0] = 10; p[1] = 20;
int *grown = realloc(p, 3 * sizeof *p);
if (grown == NULL) { free(p); return 1; }
p = grown;
p[2] = 30;
printf("%d %d %d\n", p[0], p[1], p[2]);
free(p);
return 0;
}
Expected output on a successful allocation, where applicable:
10 20 30
grown receives the tentative result. The old pointer is replaced only after success. The new element is initialized separately because realloc does not initialize the extension.
p = realloc(p, bytes) can lose the owner on failure.Use a temporary for nonzero realloc requests. Preserve the old allocation on failure and invalidate old aliases on success. Initialize the new region and handle size zero explicitly.