C Standard Library

C <stdlib.h> - realloc() Function



The C <stdlib.h> realloc() function is used to change the size of the memory block pointed to by ptr. It must be previously allocated by malloc(), calloc() or realloc() and not yet freed using a call to free() or realloc(). Otherwise, the results are undefined.

If ptr is a null pointer, the function behaves like calling malloc(), assigning a new block of size bytes and returning a pointer to its beginning.

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 newly allocated portion is undefined.

If new_size is zero, the behavior of the function is implementation-defined (it may or may not be a null pointer), but the returned pointer shall not be dereferenced.

Syntax

void* realloc (void* ptr, size_t new_size);

Parameters

ptr Specify the pointer to the memory area to be reallocated.
new_size Specify new size of the array in bytes.
size_t is an unsigned integral type.

Return Value

On success, returns a pointer to the beginning of newly allocated memory. The type of this pointer is always void*, which can be cast to the desired type of data pointer in order to be dereferenceable. On failure, returns a null pointer.

Example:

The example below shows the usage of <stdlib.h> realloc() function.

#include <stdio.h>
#include <stdlib.h>
 
int main (){
  //allocating memory for array of 5 int
  int *p1 = (int*) malloc(5*sizeof(int)); 

  //populating the array
  for(int i=0; i<5; i++)
    p1[i] = (i+1)*10;

  //displaying the array
  printf("%ld bytes allocated. Stored values: ", 
         5*sizeof(int));
  for(int i=0; i<5; i++)
    printf("%d ", p1[i]);

  //reallocating the memory 
  int *p2 = (int*) realloc(p1, 100*sizeof(int));

  //displaying the array
  printf("\n%ld bytes allocated. First 5 Stored values: ", 
         100*sizeof(int));
  for(int i=0; i<5; i++)
    printf("%d ", p2[i]);

  //deallocating previously allocated memory
  free(p2);
  return 0;
}

The output of the above code will be:

20 bytes allocated. Stored values: 10 20 30 40 50 
400 bytes allocated. First 5 Stored values: 10 20 30 40 50 

❮ C <stdlib.h> Library