Introduction
memory allocation and deallocation are one of the most important aspects of space management in a programing language . In this article, we would be discussing the deallocation of memory without using free() method. But before getting into alternatives to free() let's see what is free() method.
The "free" method in C is used to deallocate memory dynamically. The memory allocated by malloc() and calloc() is not automatically deallocated. As a result, the free() function is utilized anytime dynamic memory allocation occurs. It frees up memory, which helps to prevent memory waste.
Syntax:
free(ptr);
Also See, Sum of Digits in C
Realloc() Method
To deallocate previously allocated memory, we will use the standard library function realloc(). The "realloc()" function declaration from "stdlib.h" is shown below.
Syntax:
void *realloc(void *ptr, size_t size);
The above statement creates a new memory space with the size defined in the variable newsize. The pointer will be returned to the first byte of the memory block when the function has been executed. The new memory size might be more or lower than the old memory size. We don't know if the newly allocated memory block will point to the same place as the prior memory block. In C, the realloc function will replicate all old data into the new area. It ensures that data is kept secure.
Note: The call to realloc is equal to "free(ptr)" if "size" is zero. If the pointer “ptr” is NULL and the size is non-zero, calling realloc is the same as doing malloc(size).
You can also read about the dynamic arrays in c and Short int in C Programming