Pointers & Memory · intermediate · ~6 min

calloc — zero-initialized allocation

Get pre-zeroed memory in one call.

Lesson

void *calloc(size_t n, size_t sz) allocates n * sz bytes and zero-fills them. Use it when you want zeroed memory (counters, flags, structs that should start empty); slightly slower than malloc because of the zero-fill, but the OS may give pages that are already zero.

Note the two-argument form — calloc(10, sizeof(int)) not calloc(10 * sizeof(int)). Some compilers detect multiplication overflow when you use the two-argument form.

Common mistakes

  • Using calloc where you'd have to overwrite every byte anyway — wastes the zero-fill.
  • Confusing the signature with malloc's single-argument shape.