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.

Categorystdlib.h utilities
KindLibrary function
Header<stdlib.h>
C standardC89 / C90

📝 Syntax

void *calloc(size_t nmemb, size_t size);

⚙️ Parameters

nmemb RequiredThe number of elements to allocate.
size RequiredThe 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 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.
Web-Tutorial.com

Web-Tutorial Tech Team

A team of developers maintaining programming tutorials. Each tutorial is written and reviewed by developers with expertise in that field. We work to keep our content accurate and reliable — if you spot an issue, please let us know.

Content reviewed by MOTO · Found an error? Report it

100%

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏