liveBook · Manning

Calloc

As explained in Modern C, Third Edition

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

calloc is the array-oriented allocation function in <stdlib.h>: it reserves storage for a specified number of elements and sets every bit of the new storage to 0. section 13.1

Allocate a cleared integer array

size_t n = 44; int* values = calloc(n, sizeof *values); if (values) { /* values has allocated storage with all bits set to 0 */ free(values); } section 13.4 section 13.1

Use calloc with these constraints:

  • Pass a strictly positive element count and element size. section 13.1
  • Prefer it when an all-bits-zero representation is a valid initialization, basically for integer types. section 13.4
  • Initialize floating-point or pointer-containing objects through assignment or a type-specific initialization function instead. section 13.4
#include <stdlib.h>
void* malloc(size_t size);
void free(void* ptr);
void* calloc(size_t nmemb, size_t size);
void* realloc(void* ptr, size_t size);
void* aligned_alloc(size_t alignment, size_t size);

Shows calloc alongside malloc, free, realloc, and aligned_alloc in its standard-library interface. section 13.1

How Modern C, Third Edition covers it

How deep it goes
Defines the interface and bit-clearing behavior, then limits use to positive sizes and representations where zero bits initialize the type validly.
Examples
Uses an integer-array allocation example and contrasts calloc with assignment-based initialization for other object types.
What it assumes
Assumes familiarity with C objects, allocated storage, arrays, and explicit initialization.
What you can do after
Apply it via <stdlib.h> to obtain cleared storage for suitable dynamically allocated arrays and release that storage afterward.
How it connects
Connects dynamic allocation with malloc, free, realloc, aligned_alloc, and explicit object initialization.

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, Third Edition. The section links point to the parts of the book it draws on.