Course contentsShow
← C
Lesson 543 of 1,2198. Memory ManagementFree lesson

Contiguous allocation with calloc

Contiguous allocation with calloc

What you'll learn: How to use calloc to allocate memory for arrays while automatically clearing them to zero.

The clean slate approach

When we use malloc, we are asking the computer for a raw chunk of memory. It’s like renting a hotel room where the previous guest might have left their luggage behind; the space is yours, but it’s full of "garbage values" from whatever program used that RAM last.

calloc (short for contiguous allocation) is the more polite version of this request. Not only does it set aside space for you, but it also sends in a "cleaning crew" to set every single bit of that memory to zero.

How calloc differs from malloc

While malloc takes a single argument (the total number of bytes), calloc takes two:

  1. The number of elements you want.
  2. The size of each element.

This makes it specifically designed for arrays. By passing these two numbers, calloc does the math for you and ensures the entire block is initialized.

#include <stdio.h>
#include <stdlib.h>

int main() {
    int n = 5;

    // Allocate space for 5 integers and initialize them to 0
    // Syntax: calloc(number_of_elements, size_of_each_element)
    int *arr = (int*)calloc(n, sizeof(int));

    if (arr == NULL) {
        return 1; // Memory allocation failed
    }

    // Because we used calloc, arr[0] through arr[4] are guaranteed to be 0
    for (int i = 0; i < n; i++) {
        printf("%d ", arr[i]); // Prints: 0 0 0 0 0 
    }

    free(arr);
    return 0;
}

Why use it?

You might wonder why we don't use calloc for everything. The "cleaning" process takes a tiny bit of extra time. If you are about to immediately fill an array with data from a file or user input, zeroing it out first is a wasted step.

However, calloc is a lifesaver when you need a "fresh start," such as when creating a counter array or a frequency map where you need everything to start at zero to avoid math errors caused by leftover garbage data.

Key takeaway

Use calloc when you need an array that is automatically cleared to zero upon creation.