Explain dynamic memory allocation in C with an example

CServer Side ProgrammingProgramming

Problem

Find the sum of n numbers entered by user using dynamically allocated memory using C programming.

Solution

The Dynamic memory allocation enables the C programmers to allocate memory at runtime.

The different functions that we used to allocate memory dynamically at run time are −

  • malloc () − allocates a block of memory in bytes at runtime.
  • calloc () − allocating continuous blocks of memory at run time.
  • realloc () − used for reduce (or) extend the allocated memory.
  • free () − deallocates previously allocated memory space.

Following C program is to display the elements and calculate sum of n numbers.

Using dynamic memory allocation functions, we are trying to reduce the wastage of memory.

Example

 Live Demo

#include<stdio.h>
#include<stdlib.h>
void main(){
   //Declaring variables and pointers,sum//
   int numofe,i,sum=0;
   int *p;
   //Reading number of elements from user//
   printf("Enter the number of elements : ");
   scanf("%d",&numofe);
   //Calling malloc() function//
   p=(int *)malloc(numofe*sizeof(int));
   /*Printing O/p -
   We have to use if statement because we have to check if memory
   has been successfully allocated/reserved or not*/
   if (p==NULL){
      printf("Memory not available");
      exit(0);
   }
   //Printing elements//
   printf("Enter the elements : \n");
   for(i=0;i<numofe;i++){
      scanf("%d",p+i);
      sum=sum+*(p+i);
   }
   printf("\nThe sum of elements is %d",sum);
   free(p);//Erase first 2 memory locations//
   printf("\nDisplaying the cleared out memory location : \n");
   for(i=0;i<numofe;i++){
      printf("%d\n",p[i]);//Garbage values will be displayed//
   }
}

Output

Enter the number of elements : 5
Enter the elements :
23
34
12
34
56
The sum of elements is 159
Displaying the cleared out memory location :
12522624
0
12517712
0
56
raja
Published on 08-Mar-2021 13:39:42
Advertisements