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
EasyWrite a C program that demonstrates the use of calloc() for dynamic memory allocation with automatic zero initialization. Your program should:
- Read an integer
sizefrom the user representing the number of integers to allocate - Use
calloc()to dynamically allocate memory for an array ofsizeintegers - Check if the memory allocation was successful - if it fails, print
Memory allocation failed!and terminate the program - If allocation succeeds, print
Memory allocated and initialized to zero! - Print all the initial values in the array to demonstrate they are zero, in the format:
Initial values: [value1] [value2] [value3] ... - Read
sizeinteger values from the user and store them in the allocated array - Print all the updated values in the format:
Updated values: [value1] [value2] [value3] ... - Calculate and print the sum of all values in the format:
Sum: [value] - Use
free()to deallocate the memory - 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 30Your 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 0Like 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;
}This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Logic & Flow
1Pointers Fundamentals
What is a Pointer?Declaring PointersThe Address-Of Operator (&)The Dereference Operator (*)NULL PointersRecap: Pointer Basics4Project: Simple Text Utility
Project OverviewCounting Characters2Pointers and Arrays
Array Names as PointersArray Elements - PointersPointer ArithmeticComparing PointersRecap: Pointer Array Traversal5Pointers and Functions
Pass-by-ValuePassing Pointers to FunctionsModifying Vars via PointersA Classic Example: SwapPassing Arrays to FunctionsRecap: Function Pointer Args8Structs and Pointers
Pointers to StructsThe Arrow Operator (->)Passing Structs by ValuePassing Struct PointersDynamic Allocation of StructsRecap: Modifying Struct - Ptr11Final Recap Challenges
Recap: Dynamic String ConcatRecap: Array of StructsRecap: Word Frequency Counter3Character Arrays and Strings
Strings as char ArraysThe Null TerminatorString Input with scanfUsing strlen()Using strcpy()Using strcat()Using strcmp()Recap: Basic String Functions6Memory Management
Stack vs. Heap MemoryDynamic Allocation - malloc()Using sizeof() for AllocationChecking Allocation FailureFreeing Memory with free()Allocating with calloc()Recap: Dynamic Array