#include <stdlib.h> void *realloc(void *p, size_t size);
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.
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
.
NULL
is returned.
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.
malloc
and
reallocated by realloc
reside above the 16-megabyte line for programs
that run in 31-bit addressing mode.
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;
free
, malloc
Copyright (c) 1998 SAS Institute Inc. Cary, NC, USA. All rights reserved.