What do you mean by Dynamic memory allocation in C programming?

CServer Side ProgrammingProgramming

Dynamic Memory Allocation

  • Allocation of memory at the time of execution (run time) is known as dynamic memory allocation.

  • The functions calloc() and malloc() support allocating of dynamic memory.

  • Dynamic allocation of memory space is done by using these functions when value is returned by functions and assigned to pointer variables.

  • In this case, variables get allocated only if your program unit gets active.

  • It uses the data structure called heap for implementing dynamic allocation.

  • There is memory reusability and memory can be freed when not required.

  • It is more efficient.

  • In this memory allocation scheme, execution is slower than static memory allocation.

  • Here memory can be released at any time during the program.


Following program computes the sum of even numbers and odd numbers in a set of elements using dynamic memory allocation functions −

 Live Demo

void main(){
   //Declaring variables, pointers//
   int i,n;
   int *p;
   int even=0,odd=0;
   //Declaring base address p using malloc//
   p=(int *)malloc(n*sizeof(int));
   //Reading number of elements//
   printf("Enter the number of elements : ");
   /*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");
   //Storing elements into location using for loop//
   printf("The elements are : \n");
   printf("The sum of even numbers is : %d\n",even);
   printf("The sum of odd numbers is : %d\n",odd);


Enter the number of elements : 4
The elements are :
The sum of even numbers is : 82
The sum of odd numbers is : 35
Updated on 09-Mar-2021 08:39:33