Understanding Realloc Function in C


The realloc function in C is used to dynamically change the size of a previously allocated memory block. The function takes two arguments: a pointer to the previously allocated memory block and the new size of the memory block. The function then returns a pointer to the newly allocated memory block. If the new size is larger than the old size, the extra memory is initialized to zero. If the new size is smaller than the old size, the function may return a pointer to a new memory block with the data from the old memory block copied over.
      Syntax :
             void* realloc ( void *ptr,size_t new_size )
      Example :
             int *ptr = ( int * ) malloc( 3 * sizeof( int ) ) ;
             int *ptr = ( int * ) realloc ( ptr , 5 * sizeof ( int ) ) ;

Here is an example of how to use the realloc function:

  • The program begins by allocating memory for 3 integers using the malloc function. The pointer returned by the malloc function is assigned to the variable 'ptr'. The program then prompts the user to input 3 integers, which are stored in the memory allocated by malloc.
  • The realloc function is then used to increase the size of the memory allocated by malloc. The realloc function takes two arguments, the first being a pointer to the previously allocated memory, and the second being the new size of the memory block. In this case, the size of the memory block is increased to 5 integers.
  • After the realloc function is called, the program prompts the user to input 2 more integers which are stored in the newly allocated memory. Finally, the program prints all 5 integers stored in the memory block to the console.
  • It's worth noting that, if the realloc function fails to allocate the requested amount of memory, it returns a NULL pointer and the memory previously allocated by malloc is not deallocated and should be freed manually.

Source Code

//realloc in Pointers
#include<stdio.h>
#include<stdlib.h>
int main()
{
    //void * realloc(void *ptr,size_t new_size)
    int i;
    int *ptr=(int *) malloc(3*sizeof(int));
 
    if(ptr==NULL)
    {
        printf("Memory Not Available ...");
        exit(1);
    }
 
    printf("\nEnter 3 Nos : \n");
    for(i=0; i<3; i++)
    {
        scanf("%d",ptr+i);
    }
 
    ptr=(int *) realloc(ptr,5*sizeof(int));
    for(i=3; i<5; i++)
    {
        scanf("%d",ptr+i);
    }
 
    for(i=0; i<5; i++)
    {
        printf("%d  ",*(ptr+i));
    }
    return 0;
}
 
 
To download raw file Click Here

Output

Enter 3 Nos :
1
2
3
4
5
1  2  3  4  5

List of Programs


Sample Programs


Switch Case in C


Conditional Operators in C


Goto Statement in C


While Loop Example Programs


Looping Statements in C

For Loop Example Programs


Array Examples in C

One Dimensional Array


Two Dimensional Array in C


String Example Programs in C


Functions Example Programs in C