🚀 Learn BLE on Linux (BlueZ) – Programming Part 1
Hands-on Bluetooth Low Energy course. Special price: ₹399
Enroll Now on Udemy →C calloc vs malloc
Understand calloc in C and how it differs from malloc: zero-filled memory, two arguments and overflow safety, with a tested example.
What You Will Learn
- What calloc in C does and its exact prototype
- The two differences between calloc and malloc
- Why calloc helps avoid integer overflow bugs
- When zero-filled memory is reliable and when to be careful
- How to allocate a table of structures with calloc
Prerequisites
- Lecture on malloc in C (previous lecture)
- Understanding of arrays, structures and sizeof
- A GCC (or compatible) compiler
What Is calloc in C?
calloc in C is the second dynamic memory function you meet in this free C programming course, and it solves two annoyances of malloc at once. First, it takes the number of elements and the size of each element as separate arguments, so you no longer multiply by hand. Second, it fills the entire block with zero bytes before handing it over. The name stands for clear allocation, and it is declared in <stdlib.h> like the rest of the family.
Prototype to remember
void *calloc(size_t nmemb, size_t size); — allocates room for nmemb objects of size bytes each, sets every byte to zero and returns the address, or NULL on failure.
Compare the two calls that obtain room for five integers:
int *a = malloc(5 * sizeof *a); /* you multiply, content is garbage */
int *b = calloc(5, sizeof *b); /* library multiplies, content is zero */
calloc vs malloc: The Two Differences
| Feature | malloc | calloc |
|---|---|---|
| Arguments | One: total bytes | Two: element count and element size |
| Initial contents | Indeterminate (garbage) | All bytes set to zero |
| Multiplication overflow | Your code can silently wrap around | Library can detect it and return NULL |
| Speed | Slightly faster: no clearing pass | Slightly slower for large blocks (may be free on fresh OS pages) |
| Typical use | Buffers you will fill immediately | Arrays, counters, tables that must start at 0 |
| Failure result | NULL | NULL |
The same 8 bytes after each call
The question marks are not a typo. After malloc those bytes can be anything: leftovers from an earlier allocation, zeros, or a pattern left by the allocator. A program that reads them can appear to work on Monday and fail on Tuesday, which is why uninitialised reads are among the most frustrating bugs in C.
calloc Example in C With Output
The program below, written for this lecture, prints the bytes returned by calloc, zeroes a malloc block by hand with memset to reach the same state, and finally asks calloc for an absurdly large block to show how an impossible request fails.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdint.h>
static void show(const char *tag, const unsigned char *p, size_t n)
{
printf("%-8s:", tag);
for (size_t i = 0; i < n; i++)
printf(" %02x", p[i]);
printf("\n");
}
int main(void)
{
unsigned char *a = calloc(8, sizeof *a); /* count, size */
unsigned char *b = malloc(8 * sizeof *b);
if (!a || !b) { free(a); free(b); return 1; }
show("calloc", a, 8); /* always zeros */
memset(b, 0, 8); /* malloc needs this */
show("malloc+0", b, 8);
/* calloc multiplies for you AND checks the multiplication */
volatile size_t big = SIZE_MAX / 2;
void *huge = calloc(big, 4);
printf("calloc(SIZE_MAX/2, 4) -> %s\n", huge ? "non-NULL" : "NULL");
free(huge);
free(a);
free(b);
return 0;
}
gcc -std=c17 -Wall -Wextra -Wpedantic -o ep_calloc_vs_malloc ep_calloc_vs_malloc.c
./ep_calloc_vs_malloc
Expected output:
calloc : 00 00 00 00 00 00 00 00
malloc+0: 00 00 00 00 00 00 00 00
calloc(SIZE_MAX/2, 4) -> NULL
What the output tells you
- The first line proves calloc zero-fills: eight bytes, eight
00values. - The second line shows that malloc followed by
memset(b, 0, 8)gives the same bytes, but costs you an extra line. - The third line shows the overflow story.
SIZE_MAX / 2elements of 4 bytes would need more bytes than asize_tcan even express. calloc refuses withNULL. With malloc you would have writtenmalloc(big * 4), the multiplication would wrap to a small number, and you would receive a tiny block while believing you own a huge one.
Why the volatile variable?
In the example the huge count is stored in a volatile variable only to stop the compiler from warning about a constant it can already see is impossible. In real code the count would come from user input, a file header or a network packet, which is exactly where overflow attacks originate.
Is the Zero Fill of calloc Reliable?
Some textbooks advise not trusting calloc’s initialisation. The guarantee itself is solid: the standard says the storage is initialised to all bits zero. What the standard does not promise is what all-bits-zero means for every type. For integer types it is the value 0, and on every mainstream platform including IEEE-754 floating point targets it is also 0.0 for float and double and a null pointer for pointers. On an exotic architecture a null pointer might use a non-zero bit pattern, so strictly portable code that needs null pointers or specific floats initialises them explicitly. In everyday embedded C programming on ARM, RISC-V, AVR or x86, you can rely on calloc for counters, flags and integer tables.
When to Choose calloc, When to Choose malloc
| Situation | Better choice | Reason |
|---|---|---|
| Array of counters or histogram bins | calloc | They must start at zero |
| Lookup table where unused slots mean ’empty’ | calloc | Zero is a convenient empty marker |
| Buffer you immediately overwrite (read from a file) | malloc | Clearing first wastes time |
| Size computed from external data | calloc | Built-in overflow protection |
| Struct that contains pointers | calloc, then set pointers explicitly if strict portability matters | Zero bytes are a null pointer on mainstream platforms |
Using calloc for a Dynamic Array of Structures
The same function works for any element type, not only integers. Here is a short fragment that creates a table of ten device records, all starting with an id of 0 and an empty name, ready to be filled as devices register themselves.
struct dev {
int id;
char name[16];
};
struct dev *table = calloc(10, sizeof *table);
if (table == NULL)
return -1;
table[3].id = 42; /* other slots are still id 0, name "" */
/* ... use the table ... */
free(table);
Because calloc zeroes the whole block, every name array begins with a null terminator, which means each slot is already a valid empty string. With malloc you would have to loop and clear them yourself, and forgetting one slot would create an intermittent bug.
Common calloc Mistakes
- Swapping the arguments mentally.
calloc(sizeof(int), 5)works because the product is the same, but write the count first so the code reads naturally. - Forgetting the NULL check. calloc fails exactly like malloc does.
- Assuming a huge calloc is free. Zeroing megabytes takes time, and on a small microcontroller it can blow your timing budget.
- Assuming struct padding bytes hold meaningful data. They are zero, but do not depend on their values.
- Forgetting free. Zeroed memory still has to be released.
Performance and Security Considerations
For small blocks the speed difference between malloc and calloc is negligible, and on desktop systems calloc can be nearly free for large blocks because the operating system already hands out zeroed pages. On a bare-metal heap, though, the allocator must run a loop that writes zeros, so measure before using calloc in a time-critical path. From a security view, calloc is the safer default for array allocation because the multiplication is performed and checked inside the library, closing the classic integer-overflow hole. Zeroed memory also prevents stale data, such as an old password or key, from leaking through an uninitialised read.
Quick Recap: calloc in C
Think of calloc in C as malloc plus multiplication plus clearing. Use calloc in C when a table or counter array must start at zero, or when the element count arrives from outside your program and an overflow check matters. A calloc in C call costs a little more time on big blocks, so choose malloc when you will overwrite every byte straight away.
Summary and Key Takeaways
- calloc takes
(count, size), zero-fills the block and returnsNULLon failure. - Use it when contents must start at zero or when the count comes from an untrusted source.
- Use malloc when you will overwrite every byte immediately and speed matters.
- Zero bytes are zero integers everywhere; for pointers and floats they are zero on all mainstream platforms.
- Always check the result and always free the block.
Conclusion
The malloc and calloc pair covers the first half of the dynamic memory story: getting a block. The remaining question is what to do when the block turns out to be the wrong size. That is the job of realloc, the subject of the next lecture, and it has a subtle failure mode that catches even experienced programmers. Before you move on, modify the example above to allocate a table of structures, print it, and confirm under valgrind that a matching free leaves zero bytes in use. Practising this way is the heart of a good free embedded C course.
Frequently Asked Questions
What is the difference between malloc and calloc?
calloc takes element count and element size, zero-fills the memory and can detect multiplication overflow. malloc takes one byte count and leaves the memory uninitialised.
Does calloc initialise memory to zero?
Yes. Every byte of the block is set to zero. That means integer elements are 0, and on mainstream platforms floats are 0.0 and pointers are NULL.
Is calloc slower than malloc?
Slightly, because it must clear the block. For small blocks you will not notice. For large blocks on bare-metal systems, measure it.
Should I check the return value of calloc?
Yes, always. calloc returns NULL if memory is exhausted or if the requested size is impossible.
Can calloc be used for structures?
Yes. calloc(n, sizeof *p) works for any type, and gives you zeroed structures including empty strings in char arrays.
Do I free calloc memory with free?
Yes. Memory from malloc, calloc and realloc is all released with the same free function.
Is calloc safe to use in embedded C programming?
It follows the same rules as malloc: fine on many targets if used at start-up with checked results, but forbidden by some safety standards such as MISRA C.
Keep Going With Free Embedded C
Next up: realloc, the function that resizes a block without losing its data.

2 Comments