What is realloc?

Using the realloc() function, you can add more memory size to already allocated memory. It expands the current block while leaving the original content as it is. realloc stands for reallocation of memory.

realloc can also be used to reduce the size of the previously allocated memory.

Syntax

ptr = realloc (ptr,newsize);

The above statement allocates a new memory space with a specified size in the variable newsize. After executing the function, the pointer will be returned to the first byte of the memory block. The new size can be larger or smaller than the previous memory. We cannot be sure that if the newly allocated block will point to the same location as that of the previous memory block. This function will copy all the previous data in the new region. It makes sure that data will remain safe.

For example:

#include <stdio.h>
int main () {
   char *ptr;
   ptr = (char *) malloc(10);
   strcpy(ptr, "Programming");
   printf(" %s,  Address = %u\n", ptr, ptr);

   ptr = (char *) realloc(ptr, 20); //ptr is reallocated with new size
   strcat(ptr, " In 'C'");
   printf(" %s,  Address = %u\n", ptr, ptr);
   free(ptr);
   return 0;
} 

Whenever the realloc results in an unsuccessful operation, it returns a null pointer, and the previous data is also freed.

 

YOU MIGHT LIKE: