calloc
/ SEE-alock /
calloc is malloc's tidier cousin. Where malloc hands you a block full of leftover garbage, calloc hands you a block where every byte is set to zero. The name is usually read as cleared allocate. It also takes the size in a slightly different, often safer way: you tell it how many items, and how big each item is, separately.
Precisely: calloc(count, size) reserves a block large enough to hold count objects each of size bytes — so count * size bytes total — and then sets every byte of that block to zero before returning the pointer. For a freshly allocated array of integers this means each element starts as 0; for a struct it means every field starts zeroed (which for integers is 0, and for pointers is a null pointer on normal platforms). There is a second, quiet benefit: because calloc does the multiplication count * size itself, it can detect overflow. If count * size would wrap around past the maximum representable size, a correct calloc returns NULL instead of allocating a too-small block — a real safety win over writing malloc(count * size) by hand, where the multiply could overflow silently and hand you a buffer far smaller than you intended.
When to reach for calloc: any time you want the memory to start in a known, clean state — counters at zero, flags false, pointers null — so you do not have to initialize it yourself. When malloc is enough: when you are about to overwrite every byte anyway, in which case the zeroing is wasted work. Like malloc, calloc returns NULL on failure and must be checked, and the block must eventually be released with free().
int *scores = calloc(100, sizeof(int)); /* 100 ints, all 0 */ if (scores == NULL) return -1; /* scores[i] is already 0 for every i */ free(scores);
calloc(count, size) zeroes the whole block and guards against the count*size multiply overflowing.
All-bits-zero equals the integer 0 and (on normal platforms) a null pointer, but the C standard does not guarantee that all-bits-zero is a floating-point 0.0 or a valid null for every exotic type — rely on it for integers and pointers in practice.