C Programming :: Dynamic Memory Allocation - Discussion
11 / 18
What is the output of the following C Program?
#include
#include
void main()
{
int *mptr, *cptr;
mptr = (int*)malloc(sizeof(int));
printf("%d",*mptr);
cptr = (int*)calloc(sizeof(int),1);
printf("%d",*cptr);
}
#include
void main()
{
int *mptr, *cptr;
mptr = (int*)malloc(sizeof(int));
printf("%d",*mptr);
cptr = (int*)calloc(sizeof(int),1);
printf("%d",*cptr);
}
A0 0
Bgarbage-value 0
C0 garbge value
DCompilation Error
Show Explanation
Asked In ::
Both malloc and calloc() are library functions that
allocate memory dynamically (i.e that memory is allocated during
runtime(execution of the program) from heap segment).
malloc() allocates memory block of given size (in bytes) and returns a
pointer to the beginning of the block. malloc() doesn’t initialize the
allocated memory. If you try to access the content of memory block then
we’ll get garbage values.
calloc() allocates the memory and also initializes the allocates memory
block to zero. If you try to access the content of these blocks then
we’ll get 0.
In the given question first we are trying to access malloc allocated memory so that garbage value will be printed. and for calloc allocated memory it will print zero.
Read Full Answer
Report Error
Please Login First Click Here