Use of malloc (): It allocates a block of size bytes from memory heap. It allows a program to allocate memory as its needed, and in the exact amount needed.
Use of calloc (): It provides access to the C memory heap, which is available for dynamic allocation variable-sized block of memory.
Illustrative programs: /*Program 1: illustration of malloc ()*/ # include< stdio.h > #include< conio.h > #include< stdlib.h > void main() { int a,* ptr ; a=10; ptr =( int *) malloc (a* sizeof ( int )); ptr =a; malloc () comes under it Allocating memory to ptr
Illustrative programs(contd.): /*program 1 contd.*/ printf (“%d”, ptr ); free( ptr ); getch (); } Allocated memory is freed In this program the sizeof ( int ) is the size given thorugh malloc () to ptr . Now ptr is assigned the value of a . ptr =a; so the value 10 is assigned to ptr , for which, we dynamically allocated memory space using malloc .
Illustrative programs(contd.): Output of program 1 is:
Ilustrative programs(contd.): /*Program 2: Illustration of calloc ()*/ #include< stdio.h > #include< conio.h > #include< stdlib.h > void main() { int * ptr,a [6]={1,2,3,4,5,6}; int i ; ptr =( int *) calloc (a[6]* sizeof ( int ),2); c alloc () comes under it Allocating memory for ptr
Illustrative programs(contd.): /*program 2 contd.*/ for( i =0;i<7;i ++) { printf (“\ n%d ”,* ptr+a [ i ]); } free( ptr ); getch (); } Allocated memory is freed
Illustrative programs(contd.): In program 2 6 blocks of memory is allocated using calloc () with each block having 2 bytes of space . Now variable i is used in for to cycle the loop 6 times on incrementa l mode. On each cycle the data in allocated memory in ptr is printed using * ptr+a [ i ] . Output of program 2: