I was wondering whether calloc()
is preferable to a malloc
followed by a memset
. The latter appears to be the most common way of allocating and initializing memory.
A github code search turns up many calloc
test and implementations but in the first number of pages no code actually using calloc
.
Does anyone who knows of any projects/organizations that use or recommend using calloc
and the circumstances where recommend it?
From the comments and answers below, here's some the thoughts that have emerges so far:
calloc(n, size)
can prevent overflow that is possible with malloc(n * size)
combining malloc and memset gives calloc a chance to request a page that is known to already be zeroed.
a disadvantage to calloc that the combined steps may preclude other wrappers around malloc.
Malloc() VS Calloc(): Explore the Difference between malloc() and calloc() malloc() and calloc() functions are used for dynamic memory allocation in the C programming language. The main difference between the malloc() and calloc() is that calloc() always requires two arguments and malloc() requires only one.
If you use memset() to zero the page, memset() will trigger the page fault, cause the RAM to get allocated, and then zero it even though it is already filled with zeroes. This is an enormous amount of extra work, and explains why calloc() is faster than malloc() and memset() .
But if you ever find yourself malloc()ing a block and then setting the memory to zero right after, you can use calloc() to do that in one call." so what is a potential scenario when i will want to clear memory to zero.
Well, I use calloc
in quite a bit of C code, so I guess that's an answer. I think the slightly unusual call method (number of elements and size of element) may throw people. However, one other reason why you may not see as many calls as you would expect is that a lot of larger projects use wrappers around malloc
, calloc
, and friends that do error handling (usually terminating the program) on memory allocation failure. So the actual code uses xcalloc
instead.
One reason to use calloc
over malloc
plus memset
is that calloc
may be more efficient. If the C library already knows that a page is zeroed (perhaps it just got new zeroed memory from the OS), it doesn't have to explicitly zero it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With