CONTENTS | INDEX | PREV | NEXT
realloc
NAME
realloc - reallocate memory allocated by calloc, malloc, or strdup
SYNOPSIS
void *newptr = realloc(oldptr, bytes)
void *oldptr;
size_t bytes;
FUNCTION
realloc reallocates a previously allocated buffer, making it
larger or smaller. realloc returns a pointer to a new buffer
which might be the same as the old buffer, but might not.
data in the original buffer is copied to the new buffer and
the original buffer is freed. When extending a buffer with
realloc note that the extended bytes (beyond the original buffer)
will come up garbage.
You may pass a NULL as the first argument to realloc which basically
makes realloc a malloc.
EXAMPLE
#include <string.h>
#include <assert.h>
#include <stdlib.h>
main()
{
char *s;
int len;
s = strdup("This is a test");
assert(s);
len = strlen(s);
/*
* Remember that len does not include the nul byte at the end
* of the string
*/
s = realloc(s, len + 8); /* make more room */
assert(s);
/*
* we can use strcat since in extending the allocated string
* the nul *was* copied along with the string during the realloc.
*/
strcat(s, "xx");
puts(s); /* This is a testxx */
return(0);
}
INPUTS
void *oldptr; pointer to original allocated buffer
size_t bytes; size of new buffer
RESULTS
void *newptr; pointer to new buffer
SEE ALSO
malloc, calloc, strdup