C program implementing calloc() and free() functions
You will see a program below in C which will calculate the product of n numbers using calloc()
and free()
functions. At first, the program will ask for the size of the numbers to the users. Then we will use the calloc()
function for allocating the space according to the number of elements entered by the user. The calloc()
function works by allocating space for an array of elements, initialize them to zero and returns a void pointer to the memory. Later, the program will also check for the sufficiency of the memory and will exit from the program when the memory is not sufficient. The user will hence enter all the numbers and the program will subsequently compute the product. Later, the product will be displayed and the programmer will later use the function free()
in order to free the unused memory.
#include <stdio.h> #include <stdlib.h> int main() { int n, i, *p, mul=1; printf("Enter number of elements that you want to enter: "); scanf("%d", &n); p = (int*) calloc(n, sizeof(int)); if(p == NULL) { printf("Error! not sufficient space."); exit(0); } printf("Enter all elements: "); for(i = 0; i < n; ++i) { scanf("%d", p + i); mul *= *(p + i); } printf("The product computed is = %d", mul); free(p); return 0; }
The above code will display its output as below.
Output:
Enter elements: 1
2
3
Sum = 6