Chapter Contents

Previous

Next
realloc

realloc



Change the Size of an Allocated Memory Block

Portability: ISO/ANSI C conforming, UNIX compatible


SYNOPSIS
DESCRIPTION
RETURN VALUE
ERRORS
DIAGNOSTICS
CAUTION
IMPLEMENTATION
EXAMPLE
RELATED FUNCTIONS
SEE ALSO


SYNOPSIS

#include <stdlib.h>

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


DESCRIPTION

realloc shrinks or expands a memory block previously allocated by malloc or calloc , possibly moving it to another location. p points to the previously allocated memory block. size is the size of the new block. The contents of the old block are preserved in the new block after reallocation, unless the old size is greater than the new size. If the old size is greater, the unwanted extra bytes are lost. When the new size is larger than the old size, the contents of the new block that follow the data from the old block are unpredictable.


RETURN VALUE

realloc returns the address of the first character of the new memory block. The reallocated block is suitably aligned for storage of any type of data.

If a new memory block cannot be allocated, the contents of the location that p points to are not changed, and realloc returns NULL .


ERRORS

User ABEND 1205 or 1206 may occur if memory management data areas are overlaid.


DIAGNOSTICS

If adequate memory is not available or if 0 bytes were requested, NULL is returned.


CAUTION

When the reallocated memory block is larger than the original memory block, the contents of the added space are not initialized.

realloc is an inefficient memory allocation tool, especially when used on large blocks. Use linked lists rather than arrays expanded with realloc to improve both execution speed and memory use.


IMPLEMENTATION

Under an XA or ESA operating system, memory allocated by malloc and reallocated by realloc reside above the 16-megabyte line for programs that run in 31-bit addressing mode.


EXAMPLE

This example doubles the size of a table, if necessary, using realloc .

#include <stdlib.h>
#include <stdio.h>

char **table, **temp, *item;
unsigned table_size, max_elem;

   /* Determine if table size is too small.             */
if (max_elem >= table_size) {
   table_size *= 2;    /* Double table size.            */

      /* Allocate more space for table. */
   temp = realloc((char*)table, table_size*sizeof(char*));

      /* If reallocation is successful, copy address of */
      /*  new area to table.                            */
   if (temp)
      table = temp;
   else {
      puts("Item table overflow");
      exit(16);
   }
}
table[max_elem++] = item;


RELATED FUNCTIONS

free , malloc


SEE ALSO


Chapter Contents

Previous

Next

Top of Page

Copyright © 2001 by SAS Institute Inc., Cary, NC, USA. All rights reserved.