Resizing a Block of Memory

Sometimes you have to resize a block of dynamic memory after you have already stored data in it. The most common reason for this is the need to grow the block beyond the initial size given to the malloc() call. This often happens if the amount of data to be stored and processed is not known in advance (for example, when you are receiving data over a network connection).

The C library provides the realloc() function for this purpose. It takes two parameters: the address of the memory block to be resized and the desired new size of that block.

void *x, *y;
x = malloc(1000); // Initial block
y = realloc(x, 2000); // Doubled

Retaining the Original Address

Since realloc() can return a NULL pointer if the operation fails, ...

Get C Programming: Visual Quickstart Guide 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.