Free c library: The stdlib C Library function free deallocate a memory block which was previously allocated by a call to malloc, calloc or realloc. It makes deallocated block available for allocations.
Function prototype of free
void free(void *ptr);
- ptr : This is a pointer to a memory block to deallocate, which was previously allocated with calloc, malloc or realloc. It does nothing, if ptr is null pointer.
Return value of free
NONE
C program using free function
Free function in c: The following program shows the use of free function to deallocate memory which was previously allocated using calloc.
#include <stdio.h> #include <stdlib.h> int main(){ int *array, counter, n, sum=0; printf("Enter number of elements\n"); scanf("%d", &n); /* Allocate memory to store n integers using calloc */ array = (int*)calloc(n, sizeof(int)); /* * Take n integers as input from user and store * them in array */ printf("Enter %d numbers\n", n); for(counter = 0; counter < n; counter++){ scanf("%d", &array[counter]); } /* Find sum of n numbers */ for(counter = 0; counter < n; counter++){ sum = sum + array[counter]; } printf("Sum of %d numbers : %d", n, sum); /* Deallocate allocated memory */ free(array); return 0; }
Output
Enter number of elements 6 Enter 6 numbers 1 2 3 4 5 6 Sum of 6 numbers : 21