Loading lessons...
calloc - Allocate and Zero
calloc - Allocate and Zero
calloc allocates memory like malloc, but also zeroes every byte.
The call
int *nums = (int *)calloc(5, sizeof(int));
- First argument: number of elements.
- Second: size of each element.
The difference from malloc
calloc(5, sizeof(int)) allocates 5 ints and sets them all to 0. malloc leaves the memory as garbage.
When use calloc
- When you want zeroed arrays right away.
- Safer for beginners, no surprise garbage.
It still needs free
free(nums);
TL;DR
- calloc = allocate + zero.
- Take element count and element size.
- malloc leaves garbage; calloc clears it.
- Free it when finished.