hello,
what is the difference between calloc() and malloc()??in C ?
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.
Look up a C++ Reference and learn How To Ask Questions The Smart WayOriginally Posted by Bjarne Stroustrup (2000-10-14)
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
Compilers can produce warnings - make the compiler programmers happy: Use them!
Please don't PM me for help - and no, I don't do help over instant messengers.
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.
dwk
Seek and ye shall find. quaere et invenies.
"Simplicity does not precede complexity, but follows it." -- Alan Perlis
"Testing can only prove the presence of bugs, not their absence." -- Edsger Dijkstra
"The only real mistake is the one from which we learn nothing." -- John Powell
Other boards: DaniWeb, TPS
Unofficial Wiki FAQ: cpwiki.sf.net
My website: http://dwks.theprogrammingsite.com/
Projects: codeform, xuni, atlantis, nort, etc.