[Previous] [Contents] [Next]

realloc()

Allocate, reallocate or free a block of memory

Synopsis:

#include <malloc.h>

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

Library:

libc

Description:

The realloc() function allocates, reallocates, or frees the block of memory specified by old_blk based on the following rules:

The realloc() function allocates memory from the heap.


Note: Because it's possible that a new block will be allocated, any pointers into the old memory could be invalidated. These pointers will point to freed memory, with possible disastrous results, when a new block is allocated.

The realloc() function returns NULL when the memory pointed to by old_blk can't be reallocated. In this case, the memory pointed to by old_blk isn't freed, so be careful to maintain a pointer to the old memory block so it can be freed later.

In the following example, buffer is set to NULL if the function fails, and won't point to the old memory block. If buffer is your only pointer to the memory block, then you have lost access to this memory.

buffer = (char* )realloc( buffer, 100 );

Returns:

A pointer to the start of the reallocated memory, or NULL if there isn't sufficient memory available or size is set to zero.

Examples:

#include <stdlib.h>
#include <malloc.h>

int main( void )
{
    char* buffer;
    char* new_buffer;

    buffer = (char* )malloc( 80 );
    new_buffer = (char* )realloc( buffer, 100 );
    if( new_buffer == NULL ) {
        /* not able to allocate larger buffer */

        return EXIT_FAILURE;
    } else {
      buffer = new_buffer;
    }


    return EXIT_SUCCESS;
}

Classification:

ANSI

Safety:
Cancellation point No
Interrupt handler No
Signal handler No
Thread Yes

See also:

calloc(), free(), malloc(), sbrk()


[Previous] [Contents] [Next]