O'Reilly logo

C Programming: Visual Quickstart Guide by Marc Liyanage, Larry Ullman

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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, ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required