What is free()?
free() function is used to release the dynamiclly allocated memory in heap.
Syntax:
void free(ptr);
The memory allocated heap will not be released automatically after using the memory. The space remains there and can’t be used.
It is the programmers responsibility to release the memory after use.
Example:
int main(){
int *ptr = (int *)malloc(4*sizeof(int));
....
free(ptr);
}
Example:
#include
#include
int* input() {
int *ptr, i;
ptr = (int*)malloc(5 * sizeof(int));
if (ptr == NULL) {
printf("Memory not available.\n");
exit(1);
}
printf("Enter 5 numbers: ");
for (i = 0; i < 5; i++) {
scanf("%d", ptr + i);
}
return ptr; // Return after input is complete
}
int main() {
int i, sum = 0;
int *ptr = input();
for (i = 0; i < 5; i++) {
sum += *(ptr + i);
}
printf("Sum is %d\n", sum);
free(ptr); // Release memory after using it
ptr = NULL;
return 0;
}
Output:
Enter 5 Numbers: 10
20
30
40
50
Sum is 150
