realloc in c
Use of realloc function
Using realloc function, we can resize the memory area which is already created by malloc or calloc.
It's is also declared in stdlib.h library.
If the memory area is not created dynamically using malloc or calloc, then the behavior of the realloc function is undefined.
realloc - used to resize the memory area which is pointed by ptr.
ptr - the name of the pointer variable which needs to be resized.
new size - the new size of the memory area. It can be smaller or bigger than the actual size.
return value of realloc
If realloc request success, it will return a pointer to the newly allocated memory.
Otherwise, it will return NULL.
Changing size from 100 bytes to 1000 bytes using realloc.
How realloc works?
1.realloc will act as malloc if the pointer variable is NULL.
realloc smaller size
2.If the given size is smaller than the actual, it will simply reduce the memory size.
3.If the given size is bigger than the actual, it will check whether it can expand the already available memory.
If it is possible it will simply resize the memory.
Otherwise, realloc will create the new block of memory with the larger size and copy the old data to that newly allocated memory and than it will deallocate the old memory area.
For example assume, we have allocated memory for 2 integers.We are going to increase the memory size to store 4 integers.
If realloc unable to expand the memory size, it will do something like below,