C program implementing malloc() and free() functions.
The program below is C program which will calculate the product of n numbers using malloc()
and free()
functions. At first, the program will ask the size of the numbers they will enter. Then we will use the malloc()
function for allocating the space according to the number of elements entered by the user. The malloc()
function works by allocating requested size of bytes and returns a void pointer pointing to the first byte of the allocated space. 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.
Code:
#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*) malloc(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 program will display its output as below.
Output:
Enter elements: 1
2
3
Sum = 6