Skip to main content

Dynamic memory allocation using malloc in C

If you are a beginner in programming it may be that you got some trouble to define an array of large size.As if you are trying to allocate an array of size (10^7===10000000) like 

                                     int a[10000000];
you must got an run time error called segmentation fault.To overcome these difficulties we use a malloc function to declare a run time memory.

First we have to include header file "malloc.h" and then the following lines of codes.
#include<malloc.h>
int main()
{
     int *a;
     a=(int *)malloc(sizeof(int)*10000000); //equivalent to int a[10000000] without segmentation fault

}

If you want to declare a two dimensional array like....
int a[m][n];

Where m and n are very large number then write the following lines of codes.
int main()
{
     int **a,i;
     a=(int **)malloc(sizeof(int)*m); 
      
     for(i=0;i<n;++i)
    a[i]=(int *)malloc(sizeof(int)*n);

 // The above code same as int a[m][n]; without segmentation fault;

}

Note: Don't forget to include the "malloc.h" header file at the top of source code. and please comment If you find anything ambiguous or anything want to suggest.

Comments