C - realloc() - Extending Dynamically Allocated Memory

Introduction

The realloc() function reuses or extends memory that you previously allocated using malloc() or calloc() (or realloc()).

The realloc() function expects two argument values:

  • a pointer containing an address that was previously returned by a call to malloc(), calloc(), or realloc() and
  • the size in bytes of the new memory that you want allocated.

The function returns a void* pointer to the new memory or NULL if the operation fails for some reason.

The new memory extent can be larger or smaller than the original.

realloc() preserves the contents of the original memory area up to the lesser of the old and new memory extents.

If the new memory extent is greater than the old, then the additional memory is not initialized and will contain junk values.

Related Topics