This function helps to change the size of the memory block which has been allocated dynamically using either malloc() or calloc() function.
There can be two situations
(i). size of the memory block is to be decreased
(ii). size of the memory block is to be increased
(i). If size of the memory block is to be decreased then the extra memory locations are truncated and the process gets completed.
(ii). If size of the memory block is to be increased then the system first of all tries to allocate the additional memory locations in continuation of the existing memory block if possible.
If this is not possible then,
(a). A memory block of new size is allocated at a new location.
(b). The data from the old memory block is transferred to the newly created memory block.
( c) The old memory block is released .
(d). The base address of the newly created memory block is transferred and stored in the pointer variable.
printf(“Enter total elements”);
*p=(int *) malloc(n*sizeof(int));
Printf(“Enter new size”);
n: size of the old memory block
n1 : size of the newly created memory block.
P: base address of the old memory block.
After execution of the statement the pointer variable p will contain the base address of the newly created memory block.