C dynamic memory allocation



In this tutorial we will be learning dynamic memory allocation. It is used to allocate memory dynamically at run time.

C dynamic memory allocation

Consider the below program where we have declared an array of size 100.

#include<stdio.h>
 
int main() {
   int a[100], i;
 
   for (i = 0; i < 100; i++)
      scanf("%d", &a[i]);
 
   printf("\nPrinting array -");
   for (i = 0; i < 100; i++)
      scanf("A[%d]", &a[i]);
 
    return (0);
}

In this program we are accepting 100 numbers from the user and printing the array of size 100.

Some scenarios when you want dynamic allocation –

No Scenario
1 At run time you want to accept more numbers from user than size of array.
2 At run time you want to accept very few numbers than size of array

We cannot predict at compile time how much size is required at run time. Memory requirement can be insufficient or can be more than sufficient.

Dynamic memory allocation in c programming will allow program to allocate/release memory at run time (i.e while running program)

Important Notes

Point,Explanation
Header File,stdlib.h
Total Functions,4
Header File,stdlib.h

Dynamic Memory Allocation : malloc / Calloc function

  1. Dynamic Memory Allocation means to Allocate Memory at run-time i.e at the time of Program execution 
  2. In C malloc and calloc functions are used to allocate memory at Run-time
  3. It returns pointer to block of n bytes of memory allocated during run-time
  4. If the Process fails i.e if it is unable to allocate memory then returns NULL
  5. Note : Typecasting is necessary.

Must See :

  1. Calloc
  2. Malloc