malloc() and calloc() are functions in C that allocate memory dynamically from the heap. malloc() allocates a block of memory of a specified size, while calloc() allocates memory and initializes it to zero. Two sample programs are provided to illustrate the use of malloc() and calloc(): one program allocates memory for an integer using malloc() and assigns a value to it, while the other allocates an array of integers using calloc() and prints the values. Both programs free the allocated memory after use.
2. 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.
3. Use of calloc():
It provides access to the C memory heap, which is available for dynamic
allocation variable-sized block of memory.
4. Illustrative programs:
/*Program 1: illustration of malloc()*/
#include<stdio.h>
malloc() comes under it
#include<conio.h>
#include<stdlib.h>
void main()
{
int a,*ptr;
a=10;
ptr=(int*)malloc(a*sizeof(int));
ptr=a;
Allocating memory to ptr
5. Illustrative programs(contd.):
/*program 1 contd.*/
printf(“%d”,ptr);
free(ptr);
Allocated memory is freed
getch();
}
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.
7. Ilustrative programs(contd.):
/*Program 2: Illustration of calloc()*/
#include<stdio.h>
calloc() comes under it
#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);
Allocating memory for ptr
9. 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 incremental mode. On each cycle the data in allocated memory
in ptr is printed using *ptr+a[i].
Output of program 2: