Pointers & Memory · intermediate · ~10 min

realloc — grow or shrink

Resize a heap allocation without losing data.

Lesson

void *realloc(void *p, size_t new_size) returns a (possibly new) pointer to a block of new_size bytes. The existing data is preserved up to min(old_size, new_size). On failure it returns NULL — and the old pointer is still valid — so use a temp:

T *tmp = realloc(p, n);
if (!tmp) { /* p still valid; free or retry */ } else p = tmp;

Common mistakes

  • p = realloc(p, n) — on failure, you've overwritten p with NULL and leaked the old block.
  • Calling realloc(p, 0) — implementation-defined; may free or return a unique pointer. Avoid.