realloc

From Appmethod Topics
Jump to: navigation, search

Go Up to alloc.h Index


Header File

alloc.h, stdlib.h

Prototype

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

Description

Reallocates main memory.

realloc attempts to shrink or expand the previously allocated block to size bytes. If size is zero, the memory block is freed and NULL is returned. The block argument points to a memory block previously obtained by calling malloc, calloc, or realloc. If block is a NULL pointer, realloc works just like malloc.

realloc adjusts the size of the allocated block to size, copying the contents to a new location if necessary.

Return Value

realloc returns the address of the reallocated block, which can be different than the address of the original block.

If the block cannot be reallocated, realloc returns NULL.

If the value of size is 0, the memory block is freed and realloc returns NULL.

Portability

POSIX ANSI C ANSI C++ Win32 Win64 OS X
realloc + + + +

Example

#include <stdio.h>
#include <alloc.h>
#include <string.h>

int main(void) {
    char *str;
    /* allocate memory for string */
    str = (char *) malloc(10);
    /* copy "Hello" into string */
    strcpy(str, "Hello");
    printf("String is %s\n  Address is %p\n", str, str);
    str = (char *) realloc(str, 20);
    printf("String is %s\n  New address is %p\n", str, str);
    /* free memory */
    free(str);
    return 0;
}