The realloc API

The realloc API is used to resize an existing memory chunk—to grow or shrink it. This resizing can only be performed on a piece of memory previously allocated with one of the malloc(3) family of APIs (the usual suspects: malloc(3), calloc, or realloc[array]). Here is its signature:

void *realloc(void *ptr, size_t size);

The first parameter, ptr, is a pointer to a chunk of memory previously allocated with one of the malloc(3) family of APIs; the second parameter, size, is the new size of the memory chunk—it can be larger or smaller than the original, thus growing or shrinking the memory chunk.

A quick example code snippet will help us understand realloc:

void *ptr, *newptr;ptr = calloc(100, sizeof(char)); // error checking ...

Get Hands-On System Programming with Linux now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.