Lesson 102 +10 XP

Resizing with realloc

Resizing with realloc

Need more space? realloc grows (or shrinks) a memory block.

The call

int *nums = malloc(3 * sizeof(int));
nums = realloc(nums, 5 * sizeof(int));

Now the block fits 5 ints. The first 3 values survive the resize.

The pattern

ptr = realloc(ptr, newSize);

Important notes

  • The original data is preserved (up to the new size).
  • Additions at the end are undefined (often garbage).
  • It can return NULL on failure - check.

Memory leak trap

int *temporary = realloc(ptr, big);
if (temporary == NULL) {
    // handle failure, ptr still valid
} else {
    ptr = temporary;
}

TL;DR

  • realloc resizes an allocation, keeping old data.
  • Returns NULL on failure.
  • Assign carefully so you don't lose the pointer.
  • Free at the very end.