malloc():
Declaration:
void * malloc(size_t size);
It is used to allocate memory dynamically. The argument size is used to specify the number of bytes to be allocated.
The type size_t is defined in stdlib.h as unsigned int.
If malloc() is successful , it returns pointer to the first byte of allocated memory. It returns void pointer which can be cast to any type of pointer.
It is used as:
ptr=(datatype *) malloc (specified size);
So the ptr is of type datatype . (datatype *) is used to typecast the pointer returned.
calloc():
Declaration:
Void *calloc(size_t n,size_t size);
The calloc() function is used to allocating multiple blocks of memory. It is similar to malloc() but there are 2 differences:
1) calloc() takes two arguments. The first arguments specifies the number of blocks and the second argument specifies the size of each block.
2)The memory allocated my malloc() contains garbage value whereas the memory allocated by calloc() is initialized to zero.
But the initialization done by calloc() is not reliable. So it is advised to explicitly do the initialization.
/* Program to understand the use of malloc and calloc*/
#include<stdio.h>
#include<alloc.h>
int main()
{
int *ptr1,*ptr2,i;
//Allocating memory using calloc
ptr1=(int *) calloc(5,sizeof(int));
//Allocating memory using malloc
ptr2=(int *) malloc(5*sizeof(int));
printf(" \n----------Using calloc:-------------\n");
//Check if memory is available
if(ptr1==NULL)
{
printf("Out of memory." );
return 0;
}
//Accept the integers for calloc
for(i=0;i<5;i++)
{
printf("Enter an integer:");
scanf("%d",ptr1+i);
} //display the integers for calloc
printf("The integers entered by you are:");
for(i=0;i<5;i++)
{
printf("%d\t",*(ptr1+i));
}
printf("\n\n\n----------Using Malloc:-------------\n"); //Check if memory is available
if(ptr2==NULL)
{
printf("Out of memory." );
return 0;
} //Accept the integers for malloc
for(i=0;i<5;i++)
{
printf("Enter an integer:");
scanf("%d",ptr2+i);
} //display the integers for malloc
printf("The integers entered by you are:");
for(i=0;i<5;i++)
{
printf("%d\t",*(ptr2+i));
}
return 0;
}
0 comments: