Difference between malloc and calloc
What you'll learn: How to choose between the two primary ways of requesting dynamic memory based on whether you need your data pre-cleaned.
While both functions request a block of memory from the "heap," they behave like two different types of landlords. One hands you the keys to an apartment exactly as the previous tenant left it, while the other ensures the place is professionally cleaned before you move in.
malloc: The Fast Hand-off
malloc (memory allocation) is the quick and dirty option. You tell it exactly how many total bytes you need. It finds a spot in memory and hands you a pointer to the start of it.
The catch? malloc does not clear the memory. Whatever data was there previously—"garbage values" from old variables—remains. This makes malloc very fast, but it means you must initialize your variables before reading them, or your program will behave unpredictably.
calloc: The Fresh Start
calloc (contiguous allocation) is the tidier sibling. It takes two arguments: the number of items you want and the size of each item.
More importantly, calloc automatically "zeroes out" every single bit of the allocated memory. Every integer will be 0, and every pointer will be NULL. This prevents bugs caused by leftover garbage data, but it carries a tiny performance cost because the computer has to spend time writing zeroes across the entire block.
Seeing the Difference
Notice the syntax difference: malloc takes one math expression, while calloc takes two separate numbers.
#include <stdio.h>
#include <stdlib.h>
int main() {
int n = 5;
// Requests space for 5 integers. Contents are UNKNOWN (garbage).
int *m_ptr = malloc(n * sizeof(int));
// Requests space for 5 integers. All contents are GUARANTEED to be 0.
int *c_ptr = calloc(n, sizeof(int));
// Always clean up!
free(m_ptr);
free(c_ptr);
return 0;
}
Which one should you use?
Use malloc if you plan to immediately fill the memory with your own data (like reading a file into a buffer). Use calloc if you want a clean slate or if you want your array to start at zero by default.
Key takeaway
malloc is faster but leaves "garbage" data behind, while calloc clears the memory to zero at a small performance cost.