Back to C Programming
2026-07-155 min read

calloc()

Learn calloc() step by step with clear examples and exercises.

Why This Matters

In C programming, calloc() is a crucial function for dynamically allocating contiguous memory blocks and initializing them to zero. Understanding calloc() is essential for managing memory efficiently, especially when dealing with complex data structures such as arrays of structs or other custom data types.

Prerequisites

To fully grasp this lesson, you should be familiar with the following concepts:

  • Basic C programming (variables, constants, operators)
  • Pointers in C
  • Dynamic memory allocation using malloc() and free()
  • Understanding of structures and arrays in C

Core Concept

The calloc() function dynamically allocates an array of elements with each element initialized to zero. It takes two arguments: the number of elements you want to create (nmemb) and the size of each element (size). The total memory required is calculated as nmemb * size, and then rounded up to the nearest multiple of the system's address alignment.

#include <stdlib.h>

int main() {
int *arr;
int num_elements = 5;
int element_size = sizeof(int);

arr = (int *)calloc(num_elements, element_size);

// Now `arr` points to an array of 5 integers, all initialized to zero.
}

Worked Example

Let's create a simple program that uses calloc() to dynamically allocate memory for a 3x3 matrix of integers and then prints the matrix. We will also add error handling to check if the allocation was successful.

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

int main() {
int **matrix;
int rows = 3;
int cols = 3;
int *temp_arr;
int i, j;

// Allocate memory for a single row of integers.
temp_arr = (int *)calloc(cols, sizeof(int));
if (!temp_arr) {
fprintf(stderr, "Error: Out of memory\n");
return 1;
}

// Loop through the rows and allocate memory for each one.
matrix = (int **)malloc(rows * sizeof(int *));
if (!matrix) {
fprintf(stderr, "Error: Out of memory\n");
free(temp_arr);
return 1;
}
for (i = 0; i < rows; ++i) {
matrix[i] = temp_arr;
// Shift the temporary array pointer to the next row.
temp_arr += cols;
}

// Initialize the matrix with some values.
for (i = 0; i < rows; ++i) {
for (j = 0; j < cols; ++j) {
matrix[i][j] = i * cols + j + 1;
}
}

// Print the matrix.
for (i = 0; i < rows; ++i) {
for (j = 0; j < cols; ++j) {
printf("%d ", matrix[i][j]);
}
printf("\n");
}

// Free the allocated memory.
free(matrix[0]);
free(matrix);

return 0;
}

Common Mistakes

  1. Forgetting to include ``.
  2. Using calloc() with non-integer types (e.g., char, float) without adjusting the element size calculation.
  3. Failing to free() the allocated memory after use.
  4. Assuming that calloc() automatically initializes pointers to NULL—you must still set them to NULL before using calloc().
  5. Allocating more memory than available.
  6. Not handling errors when allocating memory, which can lead to program crashes or unexpected behavior.

Practice Questions

  1. Write a program that uses calloc() to create an array of 20 char elements and then fills it with the ASCII values for the characters 'A' through 'Z'. Add error handling for memory allocation failures.
#include <stdio.h>
#include <stdlib.h>

int main() {
char *arr;
int num_elements = 26;
int element_size = sizeof(char);

arr = (char *)calloc(num_elements, element_size);
if (!arr) {
fprintf(stderr, "Error: Out of memory\n");
return 1;
}

// Fill the array with ASCII values for 'A' through 'Z'.
for (int i = 0; i < num_elements; ++i) {
arr[i] = 'A' + i;
}

// Print the array.
for (int i = 0; i < num_elements; ++i) {
printf("%c ", arr[i]);
}
printf("\n");

free(arr);
return 0;
}
  1. Modify the worked example to use floats instead of integers. Handle errors during memory allocation.
#include <stdio.h>
#include <stdlib.h>

int main() {
float **matrix;
int rows = 3;
int cols = 3;
float *temp_arr;
int i, j;

// Allocate memory for a single row of floats.
temp_arr = (float *)calloc(cols, sizeof(float));
if (!temp_arr) {
fprintf(stderr, "Error: Out of memory\n");
return 1;
}

// Loop through the rows and allocate memory for each one.
matrix = (float **)malloc(rows * sizeof(float *));
if (!matrix) {
fprintf(stderr, "Error: Out of memory\n");
free(temp_arr);
return 1;
}
for (i = 0; i < rows; ++i) {
matrix[i] = temp_arr;
// Shift the temporary array pointer to the next row.
temp_arr += cols;
}

// Initialize the matrix with some values.
for (i = 0; i < rows; ++i) {
for (j = 0; j < cols; ++j) {
matrix[i][j] = (float)(i * cols + j + 1);
}
}

// Print the matrix.
for (i = 0; i < rows; ++i) {
for (j = 0; j < cols; ++j) {
printf("%f ", matrix[i][j]);
}
printf("\n");
}

// Free the allocated memory.
free(matrix[0]);
free(matrix);

return 0;
}
  1. Create a program that uses calloc() to allocate memory for a 5x5 matrix of doubles, initializes it with random numbers, and then finds the maximum value in the matrix. Add error handling for memory allocation failures.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int main() {
double **matrix;
int rows = 5;
int cols = 5;
double *temp_arr;
double max_value = 0.0;
int i, j;

// Allocate memory for a single row of doubles.
temp_arr = (double *)calloc(cols, sizeof(double));
if (!temp_arr) {
fprintf(stderr, "Error: Out of memory\n");
return 1;
}

// Loop through the rows and allocate memory for each one.
matrix = (double **)malloc(rows * sizeof(double *));
if (!matrix) {
fprintf(stderr, "Error: Out of memory\n");
free(temp_arr);
return 1;
}
for (i = 0; i < rows; ++i) {
matrix[i] = temp_arr;
// Shift the temporary array pointer to the next row.
temp_arr += cols;
}

// Initialize the matrix with random numbers.
srand(time(NULL));
for (i = 0; i < rows; ++i) {
for (j = 0; j < cols; ++j) {
matrix[i][j] = (double)(rand() % 100);
if (matrix[i][j] > max_value) {
max_value = matrix[i][j];
}
}
}

// Print the matrix.
for (i = 0; i < rows; ++i) {
for (j = 0; j < cols; ++j) {
printf("%f ", matrix[i][j]);
}
printf("\n");
}

// Find and print the maximum value in the matrix.
printf("Maximum value: %f\n", max_value);

// Free the allocated memory.
free(matrix[0]);
free(matrix);

return 0;
}

FAQ

Why is it important to check for errors when using calloc()?

  • Checking for errors helps ensure that your program doesn't crash due to insufficient memory, and it allows you to handle such situations gracefully.

Can I use calloc() with non-integer types like char or float?

  • Yes, but you must adjust the element size calculation accordingly. For example, if you want to allocate an array of 10 chars using calloc(), you should calculate the size as sizeof(char) * 10.

What happens if I forget to free memory allocated with calloc()?

  • If you don't free memory allocated with calloc(), it will not be released, and your program may run out of memory over time. This can lead to unexpected behavior or crashes.

Why does the memory allocated by calloc() get initialized to zero?

  • Initializing the memory to zero helps ensure that any data previously stored in the memory is erased before you use it, which can help prevent security vulnerabilities and errors.