free() Function
The free()
function in C stdlib.h is used to deallocate a block of memory that was previously allocated, making that memory available for future allocations and helping to prevent memory leaks.
Syntax of free()
void free(void* ptr);
Parameters
Parameter | Description |
---|---|
ptr | Pointer to a memory block previously allocated by malloc() , calloc() , or realloc() . |
Return Value
This function does not return a value.
Notes
If the pointer provided to free()
does not refer to a valid memory block allocated by malloc()
, calloc()
, or realloc()
, the behavior is undefined. Additionally, when free()
is called with a NULL
pointer, it performs no operation. It is important to note that free()
does not change the value of the pointer itself, leaving it pointing to an invalid location after deallocation.
Examples for free()
Example 1: Deallocating Memory Allocated with malloc()
In this example, we will allocate some memory using malloc() function, and do some computations. At the end of the program, we shall free that memory using free() function.
Program
#include <stdio.h>
#include <stdlib.h>
int main() {
int *ptr = malloc(5 * sizeof(int));
if (ptr == NULL) {
printf("Memory allocation failed\n");
return 1;
}
for (int i = 0; i < 5; i++) {
ptr[i] = i + 1;
}
for (int i = 0; i < 5; i++) {
printf("%d ", ptr[i]);
}
printf("\n");
free(ptr);
return 0;
}
Explanation:
- Memory for an array of 5 integers is allocated using
malloc()
. - The array is initialized with the values 1 through 5.
- The values are printed to the console.
- The allocated memory is deallocated using
free()
.
Output:
1 2 3 4 5
Example 2: Freeing Memory Allocated with calloc() for a Dynamic String
In this example, we will allocate some memory using calloc() function, and do some computations. At the end of the program, we shall free that memory using free() function.
Program
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main() {
char *str = calloc(20, sizeof(char));
if (str == NULL) {
printf("Memory allocation failed\n");
return 1;
}
strcpy(str, "Dynamic Memory");
printf("%s\n", str);
free(str);
return 0;
}
Explanation:
- Memory for a 20-character array is allocated using
calloc()
, which initializes the allocated memory to zero. - The string “Dynamic Memory” is copied into the allocated memory.
- The string is printed to the console.
- The allocated memory is then deallocated using
free()
.
Output:
Dynamic Memory