malloc vs calloc: Key Differences Explained with Practical Examples
What is Dynamic Memory Allocation?
Dynamic memory allocation lets a program request and release memory at run time. In C, the standard library provides four primary functions for this purpose – malloc(), calloc(), realloc(), and free() – all declared in stdlib.h.
malloc(): Allocate a Single Block of Memory
malloc() (short for "memory allocation") reserves a contiguous block of bytes and returns a pointer to the first byte. The contents of the newly allocated block are indeterminate, meaning they contain whatever bits happened to be at that location in memory.
Typical usage:
int *p = (int *)malloc(n * sizeof(int));If the request fails,
malloc() returns NULL.
calloc(): Allocate Multiple Zero‑Initialized Blocks
calloc() (short for "contiguous allocation") takes two arguments: the number of elements and the size of each element. It allocates memory for all elements and automatically sets every byte to zero, making it ideal for arrays or structures that need a clean starting state.
Typical usage:
int *p = (int *)calloc(n, sizeof(int));Like
malloc(), it returns NULL if the allocation fails.
When to Use Each Function
- malloc() – Use when you need a single block and you plan to initialize the memory yourself. It’s slightly faster because it skips the zeroing step.
- calloc() – Use when you need an array or structure that should start out with all zeros. The automatic initialization protects against accidental use of garbage values.
Syntax Overview
malloc()
void *malloc(size_t size);
calloc()
void *calloc(size_t num, size_t size);
Practical Code Examples
Example 1: Using malloc() to Store 15 Integers
#include <stdlib.h>
#include <stdio.h>
int main(void) {
int *ptr = malloc(15 * sizeof(*ptr));
if (!ptr) {
perror("malloc failed");
return EXIT_FAILURE;
}
ptr[5] = 480; // 6th element (0‑based index)
printf("Value of the 6th integer is %d\n", ptr[5]);
free(ptr);
return EXIT_SUCCESS;
}
Output: Value of the 6th integer is 480
Example 2: Using calloc() to Compute a Sum
#include <stdlib.h>
#include <stdio.h>
int main(void) {
int *ptr = calloc(10, sizeof(int));
if (!ptr) {
perror("calloc failed");
return EXIT_FAILURE;
}
int sum = 0;
for (int i = 0; i < 10; ++i) {
ptr[i] = i; // initialization is redundant but shown for clarity
sum += ptr[i];
}
printf("Sum = %d\n", sum);
free(ptr);
return EXIT_SUCCESS;
}
Output: Sum = 45
Side‑by‑Side Comparison
| Feature | malloc() | calloc() |
|---|---|---|
| Number of parameters | 1 (size) | 2 (count, size) |
| Memory state after allocation | Uninitialized (garbage) | Zero‑initialized |
| Typical use case | Single block, manual initialization | Arrays or structures needing a clean start |
| Performance | Faster (no zeroing) | Slower (zeroing overhead) |
| Safety | Higher risk of using garbage values | Lower risk due to automatic zeroing |
| Return value on failure | NULL | NULL |
| Standard header | stdlib.h | stdlib.h |
Takeaway
- Use
malloc()when you need a single block and will initialize it yourself for a small performance gain. - Use
calloc()when you require zero‑initialized memory, especially for arrays or structs, to avoid subtle bugs. - Both functions return
NULLon failure; always check before dereferencing. - Remember to free allocated memory with
free()to prevent leaks.
C Language
- C++ do‑while Loop: Syntax, Practical Examples, and Nested Loops
- Mastering C++ Pointers: Concepts, Examples & Practical Applications
- C++ Operator Overloading – A Practical Guide with Code Examples
- C++ Functions Explained with Practical Code Examples
- C# Hashtable Explained: Key-Value Storage, Operations, and Practical Examples
- Understanding Switch‑Case in C: Syntax, Examples, and Best Practices
- Dynamic Memory Allocation in C: Mastering malloc, calloc, realloc, and free
- While vs. Do‑While Loops: Clear Comparison with Practical Examples
- malloc vs calloc: Key Differences Explained with Practical Examples
- calloc() in C: Zero‑Initialized Memory Allocation and a Practical Example