Pointers & Memory · intermediate · ~8 min

calloc — zero-initialized allocation

Allocate a zeroed integer array and distinguish zeroed bytes from arbitrary object initialization.

Overview

calloc takes an element count and an element size, then allocates storage with every byte set to zero. For the integer arrays in this lesson that gives zero-valued elements. You still need an allocation-failure check and an owner who eventually calls free.

Core concepts

Use calloc(n, sizeof *p) for n elements. The two arguments describe the requested array without a multiplication in the call expression. Check the result before access.

All-bits-zero represents integer zero. Do not generalize this into a portable guarantee that zeroed bytes represent every floating-point zero or every null pointer.

The pilot exercise defines n <= 0 as an empty request returning NULL. That is the exercise's chosen contract, not a claim that every call to calloc with a zero count must return NULL.

Lesson

calloc takes an element count and an element size, then allocates storage with every byte set to zero. For the integer arrays in this lesson that gives zero-valued elements. You still need an allocation-failure check and an owner who eventually calls free.

Code examples

#include <stdio.h>
#include <stdlib.h>
int main(void) {
    int *p = calloc(3, sizeof *p);
    if (p == NULL) return 1;
    printf("%d %d %d\n", p[0], p[1], p[2]);
    free(p);
    return 0;
}

Expected output on a successful allocation, where applicable:

0 0 0

Line by line

calloc initializes the bytes for three ints. The program verifies allocation before reading any element, then frees the returned block once.

Practice tasks

  1. Predict the three printed integers.
  2. Solve All zero?.
  3. Solve Zero-initialised allocation.
  4. Explain why using malloc without initialization would not meet this contract.

Summary

calloc zeroes bytes and returns owned allocated storage. Check for failure. Integer zero initialization does not imply a universal representation rule for all C types.

Practice with these exercises