What is the purpose of realloc( )?

by Vijayaprasad 2010-02-16 10:03:08

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.


realloc() can be used for re-sizing the allocated memory. No doubt in it. But due to this, some data which is there in that memory may get corrupted. So it is better not to use the realloc function.

I think the following program will help in understanding the point.

#include<stdio.h>
int main()
{
int *ptr,*ptr_new;
int num,newsize,i;

printf("
Enter the number of elements in the array");
scanf("%d",&num);
ptr= (int *)malloc( num * sizeof(int) );
if (ptr == NULL)
{
printf("
Cannot allocate memory");
return -1;
}
for(i=0;i<num;i++)
scanf("%d",&ptr[i]);

printf("
The elements entered are ::

");
for(i=0;i<num;i++)
printf("
Address of %d ----> %u",ptr[i],&ptr[i]);

printf("
Enter the new size of the array");
scanf("%d",&newsize);

ptr_new= (int *)realloc(ptr,newsize * sizeof(int));
if (ptr_new == NULL)
{
printf("
Cannot Re-allocate memory");
return -1;
}
for(i=0;i<newsize;i++)
{
if(i >= num )
{
printf("Enter %d element ",i+1);
scanf("%d",&ptr[i]);
}
}

for(i=0;i<newsize;i++)
printf("
Address of %d ----> %u",ptr_new[i],&ptr_new[i]);

system("pause");
return 0;
}

Tagged in:

1008
like
0
dislike
0
mail
flag

You must LOGIN to add comments