Synopsys R&D Interview Question
malloc takes one arguments (number of bytes required)
calloc takes two parameters (number of blocks required, size of each block)
How can we differentiate (number of bytes required) & (number of blocks required, size of each block)
Can you give an example
I have tried with following implementation:
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
int *p1 = (int *) malloc(4*sizeof(int));
int *p2 = (int *) calloc(4, sizeof(int));
printf("\naddress=%i, value=%d,",p1, *p1);
++p1;
printf("\tnext address=%i next value=%d",p1, *p1);
printf("\naddress=%i, value=%d,",p2, *p2);
++p2;
printf("\tnext address=%i next value=%d",p2, *p2);
}
both gives same output.......
same output? could you please paste output.
wht i understand is malloc is used if we know the number of bytes in advance
calloc is used if we know the size of each block(like struct) and if we also know how many of them to be allocated (number of blocks required)
otherwise, basic purpose of malloc and calloc is same, to allocate memory.
wht u did is right. calloc may internally do the same (4*sizeof(int)) to allocate. (but initialze all its bits to '0')
malloc does not initialize the memory.
- yours.ramesh February 10, 2011calloc initialize all bits of memory allocated to 0.
malloc takes one arguments (number of bytes required)
calloc takes two parameters (number of blocks required, size of each block)