Pointers & Memory · intermediate · ~12 min

realloc — grow or shrink a heap block

Resize owned storage while preserving the original allocation on failure.

Overview

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.

Core concepts

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.

Lesson

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.

Code examples

#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

Line by line

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.

Practice tasks

  1. Explain why p = realloc(p, bytes) can lose the owner on failure.
  2. Solve Append with realloc.
  3. Solve Resize via a pointer-to-pointer, including zero size and allocation failure.
  4. Optional project after the drills: Grow a dynamic buffer.

Summary

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.

Practice with these exercises