Question

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.

Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top