hello,
what is the difference between calloc() and malloc()??in C ?
Printable View
hello,
what is the difference between calloc() and malloc()??in C ?
Why do you keep posting in C++ if you have questions about C?
The difference between them is that calloc fills the memory with 0s, which malloc does not. Also, calloc takes the size of the object you want to allocate and how many of them. Malloc only takes the entire size of the block you want to allocate.
Moved to C programming forum.
malloc() gives no guarantee of the state of the content allocated, calloc() guarantees that it's set to binary zero. [Which for most architectures means that pointers are NULL and that floating point values are zero].
There is also a difference in the way that amount of memory you allocate is specified.
--
Mats
Basically, this is calloc() defined with malloc(). :)
calloc() can do things differently, however. For example, I think some platforms can deal with lots of small chunks differently from one big chunk, and calloc() could take advantage of that. Of course, I can't think of any reason for this, since the chunks would have to be contiguous.Code:void *calloc_with_malloc(size_t n, size_t size) {
void *data = malloc(n * size);
memset(data, 0, n * size);
return data;
}
Generally, I use malloc(), even for arrays. I only use calloc() if I need zero-ed memory. I guess you could use calloc() whenever you need memory allocated for an array -- or even when you need just one element zeroed, just as you can use fread() and fwrite() for one block.