realloc : <stdlib.h> library function

The function void *realloc(void *ptr, size_t size); tries to changes the size of the memory block pointed by pointer ptr that was previously allocated using malloc or calloc. Function realloc returns the pointer to the new block of memory allocated. It may move the memory block to a new location and the content of the memory block is preserved completely, If size of final memory block is more than size of initial memory block.

Function prototype of realloc

void *realloc(void *ptr, size_t size);
  • ptr : This is a pointer to a memory block previously allocated with calloc, malloc or realloc. Argument ptr may be NULL, in this case realloc allocates a new block of size bytes.
  • size : This is the new size of memory block in bytes.

Return value of realloc

This function returns a pointer to the reallocated memory block or null pointer if it fails to reallocate memory. The type of returned pointer is always void*, which can be casted to any type of pointer.

C program to show the use of realloc function

The following program shows the use of realloc function to dynamically increase the size of an integer array.

#include <stdio.h>
#include <stdlib.h>

int main(){
    int *array, counter, n;
    int arraySize, sum=0;
    
    printf("Enter number of elements\n");
    scanf("%d", &n);
    /* Calculate size of array to store n integers */
    arraySize = n*sizeof(int);
    /* Allocate memory to store n integers using malloc */
    array = (int*)malloc(arraySize);
    /* 
     * Take n integers as input from user and store 
     * them in array 
     */
    printf("Enter %d numbers\n", n);
    for(counter = 0; counter < n; counter++){
        scanf("%d", &array[counter]);
    }
    /* Increase the size of array to twice */
    array = (int*)realloc(array, n*2);
    printf("Enter %d more numbers\n", n);
    for(counter = n; counter < 2*n; counter++){
        scanf("%d", &array[counter]);
    }
    /* Find sum of n numbers */
    for(counter = 0; counter < 2*n; counter++){
        sum = sum + array[counter];
    }
    printf("Sum of %d numbers : %d", 2*n, sum);
    
    return 0;
}

Program Output
Enter number of elements
3
Enter 3 numbers
1 2 3
Enter 3 more numbers
4 5 6
Sum of 6 numbers : 21