Realloc Function ( Dynamic Memory Allocation Part - 4 )

Defination


Sometimes we may discover that the previously allocated memory is not enough or there is a wastage of memory space which we want to end. Realloc function is a one way solution to it. We can reallocate memory and can increase or decrease the amount of memory allocation by the realloc function in the heap memory. 

Some key points to note of the realloc function. 

  • If any previous data is stored in the memory allocated by malloc or calloc though a pointer, the previous data will surely be restored as the program surely guarantees that.
  • In order to store a value in the malloc or calloc variable use strcpy in case of strings.
  • Pass the same pointer to the realloc which has been passed to create memory blocks in calloc or malloc functions.
  • If the function is unsuccessful in allocation of memory, it return a null pointer to the original block and the previous data will be lost, which is a big downside of the realloc function.
The general syntax of the calloc function is :

< data_type> *pointer; 
 pointer = ( < data _type > *)malloc( < byte size >);
 pointer  = ( < type casting * > ) realloc(pointer,< new byte size >)
 For storing float in the dynamic memory we can use :
float *pointer;
pointer= ( float* )calloc(5,sizeof( float ))
pointer= ( float*)realloc(pointer,10*sizeof(float))

A program using realloc function :

Another program on realloc :

Comments

Popular posts from this blog

Bubble Sort ( C & Python 3)

Comparison Logical and Bitwise Operator ( Java Part - 4 )

Something about me