realloc

From cppreference.com
< c‎ | memory
Defined in header <stdlib.h>
void *realloc( void *ptr, size_t new_size );

Reallocates the given area of memory. It must be previously allocated by malloc(), calloc() or realloc() and not yet freed with free, otherwise, the results are undefined.

The reallocation is done by either:

a) expanding or contracting the existing area pointed to by ptr, if possible. The contents of the area remain unchanged up to the lesser of the new and old sizes. If the area is expanded, the contents of the new part of the array are undefined.
b) allocating a new memory block of size new_size bytes, copying memory area with size equal the lesser of the new and the old sizes, and freeing the old block.

If there is not enough memory, the old memory block is not freed and null-pointer is returned.

If ptr is NULL, the behavior is the same as calling malloc(new_size).

If new_size is zero, the behavior is implementation defined (null pointer may be returned, or some non-null pointer may be returned that may not be used to access storage).

Contents

[edit] Parameters

ptr - pointer to the memory area to be reallocated
new_size - new size of the array

[edit] Return value

Pointer to the beginning of newly allocated memory or NULL if an error has occurred. The pointer must be deallocated with free().

[edit] Example

#include <stdio.h>  
#include <stdlib.h>
 
int main() 
{
    /* Allocate array A with 6 integers. */
    int* pa = realloc(NULL, 6*sizeof(int));
    if (!pa) {   /* if realloc() fails, terminate program */
       printf("realloc() failed in file %s at line %d\n", __FILE__,__LINE__);
       printf("***  PROGRAM TERMINATED  *** \n");
       exit(1);
    }
    printf("starting address of pa:   %p\n", (void*)pa);
 
    /* Allocate a single integer to provide a barrier to an expansion of pa. */
    int* pb = malloc(1 * sizeof(int));
    if (!pb) {   /* if malloc() fails, terminate program */
       printf("malloc() failed in file %s at line %d\n", __FILE__,__LINE__);
       printf("***  PROGRAM TERMINATED  *** \n");
       exit(1);
    }
 
    /* The starting address of array A changes because there is insufficient */
    /* room to expand A from 6 to 7 integers.                                */
    pa = realloc(pa, 7*sizeof(int));
    if (!A) {   /* if realloc() fails, terminate program */
       printf("realloc() failed in file %s at line %d\n", __FILE__,__LINE__);
       printf("***  PROGRAM TERMINATED  *** \n");
       exit(1);
    }
    printf("starting address of pa:   %p\n", (void*)pa);
 
    free(pa);
    free(pb);
    return 0;
}

Possible output:

starting address of A:   0x1f82010
starting address of A:   0x1f82050

[edit] See also

C++ documentation for realloc