realloc is a C language function  that resizes a previously allocated block of memory.

Syntax of Realloc in C
ptr = realloc (ptr_var,new_size);
The realloc() function in C accepts two parameters. 1.ptr_var: Is a Pointer to the memory block to be resized. This is the pointer returned by the previous calloc(), malloc(),or realloc(). If ptr_var is zero, realloc() works just like malloc().
2.new_size: New size is an unsigned integer specifying the new size of the memory block in bytes. If the value of new size is zero, realloc() free the memory stated by ptr and will return a null pointer.

The realloc() function tries to resize the block of memory pointed to by ptr to the new size stated by size. If positive, the function points to the new size block of memory.
If the realloc() in c function fails to extent the memory block then the function returns a null pointer and the original memory block will not change or alter.
We need to note onr thing about realloc() is that it can move a memory block to a different location , so any pointer pointing to an old memory block will become illegal. Errors need to be checked and handle properly because realloc() may not allocate the requested memory.

Return Value of Realloc Function in C
If the realloc() function in C is successful in allocating memory, it returns a pointer to the newly created memory block.
The memory block will have the same content as the original memory block and any additional memory will be set to zero. The pointer returned by realloc() may differ from the pointer passed as the first argument, so any pointer pointing to the original memory block must be updated.
If the memory size cannot be changed, realloc() will return a null value and will not change the original memory block.


Use cases of Realloc Function in C
Creating dynamic data structures:  realloc() function is used to create dynamic data structures like trees and linked lists , where the number of nodes in the structure can change at runtime.

Resizing arrays:   The use of the realloc() function in C is to resize or change the size of an array already allotted or allocated on the heap. This can be valuable when the program needs to store more data than was primarily or initially allocated.

Reducing memory fragmentation:   If a program repeatedly calls realloc() to change the size of a memory block, it can cause memory fragmentation, with many small unused memory blocks scattered throughout. realloc() can be used to reduce fragmentation by combining small blocks of memory into larger blocks.

Dynamic memory management:  realloc() function can be used with malloc() for dynamic memory management. This can be appropriate when a program needs to allocate memory at runtime and the necessary memory size is not known at compile time.

Memory optimization:   realloc() can be used to improve memory usage, by allocating memory only when needed and freeing it when not. This can be beneficial for programs that is essential to run for long periods of time or on systems with incomplete memory.

Expanding a buffer:  realloc() function is commonly used to expand a buffer to store more data, for e.g. when reading data from a file.


Examples of Realloc in C

1. Write a C program to create an array of 10 characters and resize or extend an array

#include <stdio.h>
#include <stdlib.h>
int main()
 {
  char* alpha_char = (char*) malloc(10 * sizeof(char));
  int j;
  for ( j = 0; j < 10; j++)
   {
    alpha_char [j] = 70 + j;
   }
  arr = (char*) realloc(alpha_char, 15 * sizeof(char));
  for (int j= 10; j < 15; j++)
   {
   alpha_char [j] = 70 + j;
  }
  for (int j = 0; j < 16; j++)
  {
   printf("%c ", alpha_char [j]);
  }
  free(alpha_char);
  return 0;
 }


Output:
F G H I J K L M N O P Q R S T
explanation:
The given code char* alpha_char = (char*) malloc(10 * sizeof(char)) creates an array of 10 characters on the heap using the malloc function and the first for loop assigns the first 10 characters to their respective indices. The arr = (char*) realloc(alpha_char, 15 * sizeof(char)) function is then used to resize the array to 15 characters and assigns the new characters.


2. Creating a dynamic buffer

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
 {
  char* name = (char*) malloc(10 * sizeof(char));
  strcpy(name, "sankalan");
  name = (char*) realloc(name, 15 * sizeof(char));
  strcat(name, "dtech!!");
  printf("%s\n", name);
  free(name);
  return 0;
 }

Output:
sankalan dtech!!
This code creates the variable name of 10 characters on the heap using (char*) malloc(10 * sizeof(char)); and copies "sankalan " into it by using strcpy(name,”Sankalan”) and then (char*) realloc(name, 15 * sizeof(char)) reallocates 15 characters and appends "dtech!!" to the name.


Advantages of Realloc() in C Language.

Dynamic Memory Allocation:
In dynamic memory management, reallock changes the size of a earlier allocated memory block. It adjusts the block size to fit the required data during the program. When scaling, it can make the block smaller or bigger. If it needs more space, realloc gets the new block, copies the old data, and gets clear of the old block.If needs less space, it can either downsize the existing block or get a new, smaller one. Careful use of reallock helps you use memory more efficiently by avoiding wastage and adjusting memory while your program is running.

Reduced Code Complexity:
Using realloc() to determine the size of memory blocks can make it easier to implement dynamic memory allocation management in a program, because it removes the need to manually manage memory blocks and copy data to them between.
Better memory management:
By using the realloc() function we can reallocate memory size , reduce the amount of memory lost due to overload and increase the amount of memory available for other parts of the program.
Flexibility:
The realloc() function provides greater flexibility when developing programs, as it can be used to allocate and replace memory as needed rather than a pre-allocated amount of memory.
Memory efficiency:
The realloc() function allows you to use memory more efficiently, allowing you to reuse blocks of memory instead of allocating new blocks to write data. This can help reduce fragmentation and increase overall efficiency.


DisAdvantage of Using Realloc
i. The realloc() function requires copying old data from the original memory block to the new memory block, which can take a long time for large arrays.
ii. The realloc() function cannot allocate the required amount of memory, in which case it will return null pointer. The programmer should check this and handle the error accordingly.
iii. When realloc() is called, the memory block need to be moved to another location in memory. This can invalidate pointers to the memory block, so the programmer must be prepared to update any existing pointers that point to the original memory.
iv. If a program repeatedly calls realloc() to resize a block of memory, it can cause memory fragmentation by spreading many small, unused blocks of memory across the heap. This can make it tough to allocate large blocks of memory.
v.Realloc () in C can be slower than allocating new memory


Previous Topic:-->> free() in C || Next topic:-->>practice example dynamic memory.