realloc()

QNX SDP8.0C Library ReferenceAPIDeveloper

Allocate, reallocate, or free a block of memory

Synopsis:

#include <stdlib.h>

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

Arguments:

old_blk
A pointer to the block of memory to be allocated, reallocated, or freed.
size
The new size, in bytes, for the block of memory.

Library:

libc

Use the -l c option to qcc to link against this library. This library is usually included automatically.

Description:

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

  • If old_blk is NULL and size is any value, then the call's behaviour is equivalent to calling malloc().
  • Otherwise, realloc() reallocates space for an object of size bytes by:
    • shrinking the size of the allocated memory block old_blk when size is smaller than the current size of old_blk
    • extending the allocated size of the allocated memory block old_blk if there is a large enough block of unallocated memory immediately following old_blk
    • allocating a new block with the appropriate size, and copying the contents of old_blk to this new block

The realloc() function allocates memory from the heap. Use free() or realloc() to free the block of memory.

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 you can free it 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 allocated memory, or NULL if an error occurred (errno is set).

Errors:

ENOMEM
Not enough memory.

Examples:

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

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

    buffer = (char* )malloc( 80 );
    if ( buffer == NULL ) {
        return EXIT_FAILURE;
    }

    new_buffer = (char* )realloc( buffer, 100 );
    if( new_buffer == NULL ) {

        /* Couldn't allocate a larger buffer.
           Remember that buffer stills point to
           allocated memory -- don't leak it! */

        free (buffer);
        return EXIT_FAILURE;
    } else {
      buffer = new_buffer;
    }

    return EXIT_SUCCESS;
}

Classification:

ANSI, POSIX 1003.1

Safety:
Cancellation pointNo
Signal handlerNo
ThreadYes
Page updated: