calloc() in C: Zero‑Initialized Memory Allocation and a Practical Example
What is calloc in C?
The calloc() function in C allocates multiple blocks of memory of equal size and initializes every byte to zero. It’s a dynamic allocation routine used for complex data structures like arrays or structs, returning a void * pointer.
While malloc() reserves a single contiguous block, calloc() requests n blocks, each of size bytes, guaranteeing they’re zeroed and contiguous.
Syntax
ptr = (cast_type *)calloc(n, size);
- Requests
nblocks, eachsizebytes. - All bytes are automatically set to zero.
- Returns a pointer to the first byte of the allocated area, or
NULLif the request fails.
Using calloc – A Sample Program
The following program demonstrates how calloc() can be used to compute the sum of the first ten terms of an arithmetic sequence.
#include <stdio.h>
#include <stdlib.h>
int main(void) {
int *ptr, sum = 0;
ptr = calloc(10, sizeof(int));
if (!ptr) {
fprintf(stderr, "Error! Memory not allocated.\n");
return EXIT_FAILURE;
}
printf("Calculating the sum of the first 10 terms:\n");
for (int i = 0; i < 10; ++i) {
ptr[i] = i;
sum += ptr[i];
}
printf("Sum = %d\n", sum);
free(ptr);
return EXIT_SUCCESS;
}
Output
Calculating the sum of the first 10 terms: Sum = 45
C Language
- Mastering C++ Vectors: Dynamic Arrays, Iterators, and Practical Examples
- C++ Polymorphism Explained: Practical Examples & Key Concepts
- C++ Functions Explained with Practical Code Examples
- C Hello World: Your First Program – A Step‑by‑Step Guide
- Master C Functions: Practical Examples of Recursion & Inline Techniques
- malloc vs calloc: Key Differences Explained with Practical Examples
- Dynamic Memory Allocation in C: Understanding malloc() with Practical Examples
- Using realloc() in C: Syntax, Best Practices & Example
- Mastering C’s free() Function: Practical Guide & Example
- Mastering Python’s strip() Method: Comprehensive Guide & Practical Examples