malloc and calloc
I know this question may be marked as a duplicate of difference between malloc and calloc but still i would like to ask it.
i know calloc initilizes the memory block,here my question is not focusussing on that part.
my question is
the definition of malloc says it allocates a block of memory of specified size.
and calloc says it allocates multiple block of memory ,each of the same size.
is this allocation of one block of memory and multiple blocks of memory is a real difference between the two?
because i feel we can do the same using malloc which can be done by calloc.
for example :
int *ptr;
ptr=(int *) malloc(100 * (sizeof(int)));
and
int *ptr;
ptr=(int *) calloc(100,sizeof(int));
would end up allocating 100 times the memory required by the int.
You are correct with your code examples ... the actual memory that is being pointed to by ptr
is going to be the same size (ie, and array on the heap of 100 int
objects). As others have mentioned though, the call to calloc
will actually zero-out that memory, where-as malloc
will simply give you a pointer to that memory, and the memory may or may not have all zeroes in it. For instance, if you get memory that had been recycled from another object, then the call to malloc
will still have the values from its previous use. Thus if you treat the memory as if it was "clean", and don't initialize it with some default values, you're going to end up with some type of unexpected behavior in your program.
calloc
fills the memory with ZERO's.
p=calloc(n, m);
is equivalent to
p=malloc(n*m);
memset(p, 0, m * n);
Thus, if you intend to set your allocated memory to zero, then using malloc
you have to compute n*m
twice, or use a temp variable, which is what calloc
does.
Edit: I've just read the ISO C standard and found that nowhere is specified that the implementation of calloc
should check if n*m
overflows, that is, if it exceeds the constant SIZE_MAX
in the C99 standard.
那么calloc
也会初始化内存块以包含与malloc
不同的零。
上一篇: calloc和malloc跟memset有什么区别?
下一篇: malloc和calloc