Menu
Coddy logo textTech

Allocating with calloc()

Part of the Logic & Flow section of Coddy's C journey — lesson 36 of 63.

While malloc() is the most common function for dynamic memory allocation, C provides another useful alternative: calloc(). The calloc() function, which stands for "contiguous allocation," offers a convenient way to allocate memory for arrays with an important added benefit.

Unlike malloc() which takes a single argument (total bytes), calloc() takes two arguments: the number of elements you want to allocate and the size of each element. This makes it particularly intuitive when working with arrays. For example:

#include <stdlib.h>

// Allocate space for 5 integers using calloc()
int *arr = (int*)calloc(5, sizeof(int));

// This is equivalent to: malloc(5 * sizeof(int))

The key advantage of calloc() is that it automatically initializes all allocated memory to zero. When you use malloc(), the allocated memory contains whatever random values were previously stored there, but calloc() guarantees that every byte is set to zero. This means all integers will be 0, all floats will be 0.0, and all pointers will be NULL.

Like malloc(), calloc() returns a pointer to the allocated memory or NULL if allocation fails, so you should always check for allocation failure and remember to free() the memory when you're done using it.

challenge icon

Challenge

Easy

Write a C program that demonstrates the use of calloc() for dynamic memory allocation with automatic zero initialization. Your program should:

  1. Read an integer size from the user representing the number of integers to allocate
  2. Use calloc() to dynamically allocate memory for an array of size integers
  3. Check if the memory allocation was successful - if it fails, print Memory allocation failed! and terminate the program
  4. If allocation succeeds, print Memory allocated and initialized to zero!
  5. Print all the initial values in the array to demonstrate they are zero, in the format: Initial values: [value1] [value2] [value3] ...
  6. Read size integer values from the user and store them in the allocated array
  7. Print all the updated values in the format: Updated values: [value1] [value2] [value3] ...
  8. Calculate and print the sum of all values in the format: Sum: [value]
  9. Use free() to deallocate the memory
  10. Print Memory freed! to confirm the cleanup

Remember to include the <stdlib.h> header to use calloc() and free(). This challenge demonstrates the key advantage of calloc() over malloc(): automatic initialization of all allocated memory to zero.

For example, if the input is:

3
10 20 30

Your output should be:

Memory allocated and initialized to zero!
Initial values: 0 0 0
Updated values: 10 20 30
Sum: 60
Memory freed!

This challenge highlights how calloc() provides a clean, predictable starting state for your dynamically allocated arrays, eliminating the unpredictable garbage values that malloc() might leave behind.

Cheat sheet

The calloc() function provides dynamic memory allocation with automatic zero initialization.

Syntax:

void* calloc(size_t num_elements, size_t element_size);

Key differences from malloc():

  • Takes two arguments: number of elements and size of each element
  • Automatically initializes all allocated memory to zero
  • More intuitive for array allocation

Example usage:

#include <stdlib.h>

// Allocate space for 5 integers using calloc()
int *arr = (int*)calloc(5, sizeof(int));

// This is equivalent to: malloc(5 * sizeof(int))
// But all values are guaranteed to be 0

Like malloc(), calloc() returns a pointer to allocated memory or NULL if allocation fails. Always check for allocation failure and use free() to deallocate memory when done.

Try it yourself

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

int main() {
    int size;
    
    // Read the size of the array
    scanf("%d", &size);
    
    // TODO: Write your code below
    // Use calloc() to allocate memory for the array
    // Check if allocation was successful
    // Print initial values (should be zero)
    // Read and store the input values
    // Print updated values
    // Calculate and print the sum
    // Free the allocated memory
    
    return 0;
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Logic & Flow