liveBook · Manning

Calloc

As explained in Modern C

calloc is a C standard library function that allocates storage for an array of elements and initializes all allocated bits to zero.

calloc is the C standard library’s “clear allocate” function: it dynamically allocates storage for an array and sets every allocated bit to 0. Like malloc, it returns void* storage that can serve different object types. section 13.1

TAKEAWAY: Use calloc when cleared dynamically allocated storage is suitable.

  • calloc belongs to the stdlib.h allocation interface alongside malloc, free, realloc, and aligned_alloc. section 13.1
  • Its array-oriented allocation complements malloc’s byte-based storage model, while sizeof helps express the required size from the pointed-to type. section 13.1
  • Choosing calloc instead of malloc can avoid a class of problems caused by uninitialized dynamically allocated objects; more complicated structures still need specific initialization. section 15.0

A cleared dynamic array

Suppose a program must create storage for one element per living person. The allocation’s required size depends on the number of elements and the element type; calloc is the specialized choice when the newly allocated bits should begin at zero. A related feasibility exercise asks you to compute the size of a large vector on your platform before attempting the allocation. section 13.1

How Modern C covers it

How deep it goes
Defines calloc as a malloc specialization and relates it to void* storage, but does not develop implementation details.
Examples
Uses a large vector allocation and a platform-size feasibility exercise to contextualize dynamically allocated storage.
What you can do after
Apply it via stdlib.h when dynamically allocated storage should begin with all allocated bits cleared.
How it connects
Connects calloc with malloc, free, realloc, aligned_alloc, void* pointers, sizeof, and dynamic allocation.

Also explained in

Compare how 2 books explain calloc →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Modern C. The section links point to the parts of the book it draws on.