Malloc vs Calloc in C: What's the Difference?
If you've started working with dynamic memory in C, you've almost certainly run into both malloc and calloc. They look similar, they're both used to allocate memory on the heap, and beginners often use them interchangeably without understanding what actually separates them. Here's the real difference.
What Malloc Does
malloc (memory allocation) reserves a block of memory of a given size and returns a pointer to the start of that block. Here's a simple example:
int *arr = malloc(5 * sizeof(int));
This reserves enough memory to hold 5 integers. The important part: that memory is not initialized. It contains whatever garbage values happened to already be sitting in that part of memory. If you try to read from it before writing to it, you'll get unpredictable results.
What Calloc Does
calloc (contiguous allocation) also reserves memory, but it takes two arguments instead of one, and it guarantees the memory is zeroed out:
int *arr = calloc(5, sizeof(int));
The first argument is the number of elements, the second is the size of each element. Functionally this reserves the same amount of memory as the malloc example above, but every byte is explicitly set to zero before it's handed back to you.
Why the Initialization Difference Matters
This distinction isn't just a technical footnote, it directly affects program correctness. If you allocate an array with malloc and forget to initialize every element before using it, you can end up reading garbage data, which leads to bugs that are hard to reproduce because the "garbage" changes depending on what was previously in memory.
calloc removes that risk for the specific case where you want your array to start at zero, which is extremely common when building counters, accumulators, or arrays you intend to fill in gradually.
Performance Considerations
Because calloc has to zero out every byte it allocates, it does slightly more work than malloc, which just reserves space and returns immediately. For small allocations this difference is negligible. For very large allocations in performance-critical code, some developers prefer malloc combined with a manual memset only on the parts of memory they actually need zeroed, but this is a micro-optimization that rarely matters for typical programs.
Which Should You Use?
Use calloc when you need memory that starts at zero, particularly for arrays where you're not immediately filling every slot. Use malloc when you're about to overwrite the entire block anyway, since the zeroing step in calloc would just be wasted work.
Both require a matching call to free() once you're done with the memory, regardless of which one you used to allocate it.