free() function in C language
Introduction
In a dynamic allocation, a block of memory of a specific size is put aside at runtime for only the use of the allocation process.
For managing dynamic memory, the C programming language includes several complementary features. The default library functions malloc(), realloc(), and free() that are defined in the "stdlib.h" header were the most frequently used. Each procedure allots space to an operation, modifies its capacity, and releases the memory again.
Since we take resources from the operating system's resources each time, we assign them to a program, controlling dynamic memory when programming rigorously is crucial. Utilizing dynamic memory incorrectly may have disastrous effects on the procedures active in the system's memory at that moment.
Syntax
void free(void *ptr);
Parameters of free() in C
- In C, free accepts only one parameter.
- ptr: This is a pointer or a reference to a memory block that needs to be freed up. The library functions malloc(), calloc(), and realloc() are used to allocate the memory. Nothing happens if a null pointer is provided as an argument.
Description of Free() function
A particular amount of temporarily allocated memory is released using the free() function.
The memory that changes can be allocated by invoking the malloc() function with the desired region's size in bytes as its input argument. As an outcome, the above function returns the "Ptr" pointer, which points towards the freshly allocated space.
- The free() function releases the allocated memory space, referred to by "Ptr" in its only input parameter, and notifies the OS of its availability.
- The "errno.h" headers do not provide a warning declaration for this function, nor do they provide any results.
- The "stdlib.h" header contains a definition for the free() function, a standard library component.
One must incorporate this header into your code in the following way if you want to make use of it and the other dynamic memory control functions:
#include<stdlib.h>
How to Free Dynamically Allocated Memory Using the Free() Function
In this example, we make a very basic terminal program that enables us to allocate memory using the malloc() method and release memory using the free() function. After that, we launch the program and compile the code while maintaining a watch on the system and seeing the results.
The required headers are first added, and then the main() method is opened to receive an empty return. This creates the console area of the application. In it, we define the "Ptr" pointer, which is utilized in the malloc() and free() procedures to save references to the spaces of memory that have been allocated.
The program shows its PID by utilizing the printf ()function and getpid() function after the required variables have been declared. A list with two choices is displayed before the software goes into an endless loop. The number returned by an option's scanf() method is used to get the user-selected item, which serves as the condition for a switch with two cases one for each option and the user-selected item as its condition.
- The process gets a 122 MB block of memory thanks to the malloc() method that is invoked by option 1. Option 2 calls the free() method to release that block, in contrast.
The following example shows how this application's whole code looks:
Example
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
void main()
{
int option;
char *Ptr;
int size=65000000;
printf("\process ID: %i\n",getpid());
while (1){
printf ("\n[1] Release memory.\n[2] Allocate memory.\n");
scanf("%i", &option);
switch (option){
case 1:
printf("\nAllocating memory...\n");
Ptr=malloc(size*sizeof(char));
break;
case 2:
printf("\nReleasing memory...\n");
free(Ptr);
break;
}
}
}
Output
![free() function in C language](https://static.tutorialandexample.com/c/free-function-in-c-language1.png)
Return value of free in c
- In C, free doesn't produce a value. It has a void return type.
Example of free in C
#include <stdio.h>
#include <stdlib.h>
int main()
{
int *ptr = (int *) malloc(sizeof(int));
*ptr = 6;
printf("*ptr = %d", *ptr);
free(ptr);
printf("\nptr = %d", ptr);
ptr = NULL;
printf("\nMemory at runtime!");
return 0;
}
Output
![free() function in C language](https://static.tutorialandexample.com/c/free-function-in-c-language2.png)
Explanation
An integer memory block that was assigned using the malloc() method was freed up in this program using the free() function. Throughout program execution, we released the memory referenced to by the ptr pointer variable.
Initially we used the malloc() method to construct an integer storage block, and then we placed an address of the integer block as the function's return value in the variable containing the pointer ptr (let the address be 1000). Utilizing the ptr variable, we have stored the integer value 6 within the integer block.
Exceptions of free in C
- If ptr value does not match the value provided by malloc(), calloc(), or realloc(), the behavior is undefined or uncertain.
- If ptr references a memory block that was previously freed up and no more calls to malloc(), calloc(), or realloc() resulted in a pointer which is equivalent to ptr, the behavior is not defined.
More Examples
- A program written in C that uses the free() method to free up a memory block that has been allocated using the malloc() function
Code
#include <stdio.h>
#include <stdlib.h>
int main() {
char *p1 = (char *)malloc(sizeof(char));
if (p1 == NULL) {
printf("Null pointer, Memory error!\n");
} else {
*p1 = 'A';
printf("%c", *p1);
}
free(p1);
printf("\n%c ", *p1);
p1 = NULL;
return 0;
}
Output
![free() function in C language](https://static.tutorialandexample.com/c/free-function-in-c-language3.png)
Explanation
In the above program, we've de-allocated a memory block that was allocated with the malloc() method utilizing the free() function. During the course of the program's execution, the memory referred to by the p character pointer variables was freed up.
- 2.De-allocating a memory block utilizing the calloc() function and the free() function in a C program
Code
#include <stdio.h>
#include <stdlib.h>
int main() {
int size;
scanf("%d", &size);
char *str = (char *)calloc(size, sizeof(char));
if (str == NULL) {
printf(" NULL pointer, !\n");
} else {
for (int i = 0; i < size; i++) {
char c;
scanf("%c", &c);
*(str+ i) = c;
}
for (int i = 0; i < size; i++) {
printf("%c", *(str + i));
}
}
free(str);
str = NULL;
return 0;
}
Output
![free() function in C language](https://static.tutorialandexample.com/c/free-function-in-c-language4.png)
Explanation
The calloc() function was used to allocate the char array in this application, and the free() function was utilized to release it. During the program's execution, we freed up the memory referenced by the str char pointer variable.
- Deallocating memory blocks for arrays that have been allocated in C utilizing malloc() and calloc() and free:
Code
#include <stdio.h>
#include <stdlib.h>
int main()
{
int n;
scanf("%d", &n);
int *array1 = (int *)malloc(n * sizeof(int));
int *array2 = (int *)calloc(n, sizeof(int));
if(array1 == NULL || array2 == NULL)
{
printf("Memory cannot be allocated\n");
}
else
{
for (int i = 0; i < n; i++)
{
*(array1 + i) = i;
*(array2 + i) = 10 - i;
}
free(array1);
free(array2);
printf("Memory freed ")
return 0;
}
Output
![free() function in C language](https://static.tutorialandexample.com/c/free-function-in-c-language5.png)
Explanation
In this program, the memory blocks created with the help of the malloc() and calloc() procedures were released using the free() function. Over the course of the program's execution, we reallocated the memory referenced to the two integer pointer variables array1 and array2.
When should we use free() Function?
Once you've finished utilizing memory that has been created with Malloc, Calloc, etc., you should always use Free. When you return the address from the function or store it within a data structure such as a list, this may not happen in the exact same function, but it must happen eventually for a program to be considered to leak memory.
Uses of free() function in C
The free function in C is utilized to release the memory allocated by functions such as malloc() and calloc(). A pointer pointing to the memory area that needs to be released and de-allocated is the only input required by free (ptr). The C free() method doesn't return anything. The return type is void.
- Calling the free() function is necessary for releasing the memory that was used by the malloc() or calloc() operations. If not, it will continue to utilize memory until the program exits.
Conclusion
- Free is a library function in the C language that can be found in the stdlib.h header file.
- Free(ptr) accepts only one parameter, a pointer referring to the memory region that has to be de-allocated, and it's utilized to de-allocate or free up the space allocated by functions like malloc() and calloc().
- The C free() function cannot generate a value. It has a void return type.