calloc(3)
C library function
Allocates an array of nmemb elements of size bytes, sets every byte to zero and checks that nmemb * size does not overflow. Returns NULL on failure.
#include <stdlib.h>
void *calloc(size_t nmemb, size_t size);Description
calloc reserves room for an array of nmemb elements of size bytes each, and does two things that malloc(3) does not. First, it sets every byte to zero: the C23 standard says the space is “initialized to all bits zero”. Second, it takes the two dimensions separately and refuses the allocation if their product overflows. The C23 wording is explicit: calloc returns a pointer “or a null pointer if the space cannot be allocated or if the product nmemb * size would wraparound size_t”.
That second guarantee is what makes calloc the right choice as soon as one of the dimensions comes from outside your program. malloc(nmemb * size) leaves the multiplication to you, and a product that overflows wraps around to a small number: you allocate a few bytes while believing you have billions, then write past the end. That is a real security hole.
Be careful with “all bits zero”: on common machines, a pointer and a double with every bit at zero do read as NULL and 0.0, but the standard does not promise it. For integers and characters, zero is zero, with no caveat.
Return value
The address of the zeroed block, or NULL if the allocation fails or if nmemb * size overflows. As with malloc, test this return value before you use it.
Example
#include <stdio.h>#include <stdlib.h>
int main(void){ int *scores = calloc(3, sizeof(int));
if (scores == NULL) return 1; printf("%d %d %d\n", scores[0], scores[1], scores[2]); free(scores); return 0;}$ gcc -Wall -Wextra -g zeros.c -o zeros$ ./zeros0 0 0Pitfalls
Thinking
callocis just a slowermalloc: the zeroing and the overflow check are useful guarantees you would otherwise write yourself.Mixing up the arguments with those of
memset: it iscalloc(nmemb, size), two dimensions.Counting on
0.0orNULLfor floating-point values and pointers: true in practice, not guaranteed by the standard.Forgetting the free(3): a block from
callocis freed exactly like a block frommalloc.
calloc
Write gm_calloc on top of malloc: return NULL when nmemb * size would overflow, otherwise zero every byte of the new block.