0Pricing
C Academy · Lesson

Growing with realloc

Resize a dynamic array.

When One malloc Isn't Enough

Sometimes you allocate an array, fill it, and then discover you need more room. You can't just write past the end.

realloc lets you resize an existing heap block, keeping the data that was already there.

The realloc Signature

realloc(ptr, new_bytes) takes the old pointer and the new total size in bytes.

It returns a pointer to a block of the new size. The first part of the data is preserved up to the smaller of the old and new sizes.

int *bigger = realloc(a, new_n * sizeof(*a));

All lessons in this course

  1. Allocating an Array
  2. Growing with realloc
  3. A Reusable Vector Type
  4. Freeing and Avoiding Leaks
← Back to C Academy