calloc() Allocate and zero-initialize an array
calloc() Allocate and zero-initialize an array
calloc() zero-initializes bytes or returns NULL. All-bits-zero need not represent null pointers or floating-point zero; check nmemb * size for overflow.
| Category | stdlib.h utilities |
|---|---|
| Kind | Library function |
| Header | <stdlib.h> |
| C standard | C89 / C90 |
📝 Syntax
void *calloc(size_t nmemb, size_t size);
⚙️ Parameters
| nmemb Required | The number of elements to allocate. |
|---|---|
| size Required | The size of each element in bytes. |
Returns: Returns a pointer to the zero-initialized storage on success, or NULL on failure.
▶ Example
Edit the C code below and click Run; the server compiles and executes it:
Output:
0 0 0 0
⚠️ Warning Check for allocation failure and free the storage. Do not assume an allocation succeeds when the element count and size are large.
💡 Tip calloc() zeroes the byte representation; for int on common desktop platforms, as in this example, that produces the value zero.
🏷️ Related stdlib.h functions
📚 Related Tutorials
❓ FAQ
QWhat is the main difference between calloc and malloc?
Acalloc takes an element count and element size and zeroes the storage; malloc takes a total byte count and leaves contents uninitialized. Both require a NULL check and free().
QDoes memory allocated by calloc still need to be freed?
AYes. calloc and malloc use the same dynamic-memory management, so pass the original pointer to free() when the storage is no longer needed.
QAfter calloc zeroes memory, are pointers necessarily NULL and floating-point values necessarily 0.0?
ANot necessarily. calloc guarantees that every allocated byte is zero, but ISO C does not require null pointers or floating-point 0.0 to use an all-zero bit representation on every implementation. Initialize objects explicitly when those semantic values are required instead of relying on zeroed memory alone.