Turn Desktop View Off
You are here:   HomeData StructuresBasic of Data StructureWhat is the difference between realloc() and free()
by Dinesh Thakur Category: Data Structure

The function realloc () is used to resize the memory allocated earlier by function malloc () to a new size given by the second parameter of the function. The function realloc(ptr,n) uses two arguments.the first argument ptr is a pointer to a block of memory for which the size is to be altered. The second argument n specifies the new size. The size may be increased or decreased.

If n is greater than the old size and if sufficient space is not available subsequent to the old region, the function realloc( ) may create a new region and all the old data are moved to the new region.

Illustrates malloc() and realloc ().

#include <stdio.h>


#include<stdlib.h>

int main ()

{

  int a= 0, n, m, i, j,k =0;

  int* Array;

  clrscr();

  printf("Enter the number of elements of Array.");

  scanf("%d", &n );

  Array= (int*) malloc( n* sizeof(int) );

  if( Array== NULL)

  {

     printf("Error. Out of memory.\n");

     exit(0);

  }

  printf("Enter the %d elements of Array:", n);

   for ( i =0; i<n; i++)

    scanf("%d",&Array[i]);

    for( j =0;j<n; j++)

      printf("Array[%d] = %d\n", j, *(Array+j));

      printf("Enter the number of elements of extended array.");

      scanf("%d", &m);

      Array= realloc(Array, m);

      if( Array== NULL)

       {

         printf("realloc has failed.\n");

         exit(0);

       }

       printf("Enter values of %d additional elements of array.", m-n);

       for (k= n ; k<m; k++)

         scanf("%d", &Array[k]);

          for( a =0;a<m; a++)

          printf("Array[%d] = %d\n", a, *(Array+ a));

          return 0;

}

What is the purpose of realloc( )





Subscribe To Free Daily Newsletter!

Get Free News Updates Delivered Directly To Your Inbox
About Dinesh Thakur

Dinesh ThakurDinesh Thakur holds an B.SC (Computer Science), MCSE, MCDBA, CCNA, CCNP, A+, SCJP certifications. Dinesh authors the hugely popular Computer Notes blog. Where he writes how-to guides around Computer fundamental , computer software, Computer programming, and web apps. For any type of query or something that you think is missing, please feel free to contact us.



What's New and Popular





Search Content







Advance Courses



Basic Courses



Advertise with Us