calloc
calloc(nmemb, size) allocates space for nmemb objects of size bytes each, zeros every byte, and returns the block — or NULL on failure. It is malloc plus memset plus an overflow check on the product.
Detailed Explanation
Zeroed storage is the right default for a struct you will fill field by field, for a hash table's bucket array, and for any buffer where a leftover heap byte would be a secret or a wild pointer. calloc does that in one call. A quality libc also detects nmemb * size overflow and returns NULL instead of allocating a wrapped size. malloc(nmemb * size) does not detect that unless you write the check.
The pointer rules match malloc: alignment, free exactly once, NULL on failure, thread-safe, not async-signal-safe. calloc(0, size) and calloc(nmemb, 0) are the zero-size case with the same implementation-defined pointer-or-NULL rule.
Zeroing is not free. A multi-megabyte calloc that you immediately overwrite is a wasted page-touch. Some operating systems give calloc zero-filled pages that are cheap until you write them (copy-on-write from a zero page). That makes calloc of a huge sparse table attractive. Overwriting every byte still costs.
calloc is not a constructor. Pointer members are NULL, integers are 0, which is often the empty state you wanted. If zero is not a valid state — a descriptor that must be -1 — you still have an init function.
Do not calloc and then realloc in a tight loop expecting zeros in the new tail; realloc does not zero the extension. Zero the new part yourself, or calloc a new block and copy.
Code Examples
#include <stdio.h>
#include <stdlib.h>
struct Node {
int value;
struct Node *next;
};
int main(void)
{
struct Node *n = calloc(1, sizeof *n);
if (n == NULL) {
return 1;
}
printf("%d %p\n", n->value, (void *)n->next);
/* prints: 0 0x0 (or equivalent NULL) */
free(n);
return 0;
}#include <stdio.h>
#include <stdlib.h>
int main(void)
{
size_t n = 4;
int *p = calloc(n, sizeof *p);
if (p == NULL) {
return 1;
}
printf("%d %d\n", p[0], p[3]); /* prints: 0 0 */
free(p);
return 0;
}Common Gotchas
Prefer `calloc` over `malloc` + `memset` when you want zeros
the overflow check is extra safety.
Huge `calloc` that you fully overwrite still pays for the write
if you do not need zeros, `malloc`.
Failure is still `NULL`
do not assume zeroed memory exists.
`realloc` of a `calloc`'d block does not zero new bytes
`realloc` of a `calloc`'d block does not zero new bytes