What is realloc()?
realloc() is a function of C library for adding more memory size to already allocated memory blocks. The purpose of realloc in C is to expand current memory blocks while leaving the original content as it is. realloc() function helps to reduce the size of previously allocated memory by malloc or calloc functions. realloc stands for reallocation of memory.
Syntax for realloc in C
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. The realloc function in C 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; }
How to use realloc()
The below program in C demonstrates how to use realloc in C to reallocate the memory.
#include <stdio.h> #include <stdlib.h> int main() { int i, * ptr, sum = 0; ptr = malloc(100); if (ptr == NULL) { printf("Error! memory not allocated."); exit(0); } ptr = realloc(ptr,500); if(ptr != NULL) printf("Memory created successfully\n"); return 0; }
Result of the realloc in C example:
Memory created successfully
Whenever the realloc results in an unsuccessful operation, it returns a null pointer, and the previous data is also freed.
0 Comments