realloc()
it is used to extend or reduce previously allocated memory using malloc or calloc functions. It won’t actually add or remove new blocks. It will just create a parallel memory and copy old data into it. Newly allocated blocks of un-initialised.
Â
syntax:
void *realloc(void *ptr,n);
Â
where
ptr – pointer of previously allocated memory
n – size of new memory required
Â
Eg:
int *ptr=(int *)malloc(sizeof(int));
ptr=(int *)realloc(ptr,2*sizeof(int));
Â
where
ptr is the starting byte of existing memory
n is new memory blocks we want
Â
//Example program
#include<stdio.h>
Â
void main()
{
   int i;
   int *ptr=(int*)malloc(2*sizeof(int));
Â
   if(ptr==NULL)
   {
       printf(“Memory not available”);
       exit(1);
   }
   printf(“Enter the two numbers:n”);
Â
   for(i=0;i<2;i++)
   {
       scanf(“%d”,ptr+i);
   }
Â
   ptr=(int *)realloc(ptr,4*sizeof(int));
   if(ptr==NULL)
   {
       printf(“Memory not available”);
       exit(1);
   }
   printf(“Enter 2 more integers:n”);
   for(i=2;i<4;i++)
   {
       scanf(“%d”,ptr+i);
   }
Â
   for(i=0;i<4;i++)
   {
       printf(“%d “,*(ptr+i));
   }
}
Â