Difference between malloc and calloc?
What is the difference between doing:
ptr = malloc (MAXELEMS * sizeof(char *));
or:
ptr = calloc (MAXELEMS, sizeof(char*));
When is it a good idea to use calloc over malloc or vice versa?
Solution 1:
calloc()
gives you a zero-initialized buffer, while malloc()
leaves the memory uninitialized.
For large allocations, most calloc
implementations under mainstream OSes will get known-zeroed pages from the OS (e.g. via POSIX mmap(MAP_ANONYMOUS)
or Windows VirtualAlloc
) so it doesn't need to write them in user-space. This is how normal malloc
gets more pages from the OS as well; calloc
just takes advantage of the OS's guarantee.
This means calloc
memory can still be "clean" and lazily-allocated, and copy-on-write mapped to a system-wide shared physical page of zeros. (Assuming a system with virtual memory.)
Some compilers even can optimize malloc + memset(0) into calloc for you, but you should use calloc explicitly if you want the memory to read as 0
.
If you aren't going to ever read memory before writing it, use malloc
so it can (potentially) give you dirty memory from its internal free list instead of getting new pages from the OS. (Or instead of zeroing a block of memory on the free list for a small allocation).
Embedded implementations of calloc
may leave it up to calloc
itself to zero memory if there's no OS, or it's not a fancy multi-user OS that zeros pages to stop information leaks between processes.
On embedded Linux, malloc could mmap(MAP_UNINITIALIZED|MAP_ANONYMOUS)
, which is only enabled for some embedded kernels because it's insecure on a multi-user system.
Solution 2:
A less known difference is that in operating systems with optimistic memory allocation, like Linux, the pointer returned by malloc
isn't backed by real memory until the program actually touches it.
calloc
does indeed touch the memory (it writes zeroes on it) and thus you'll be sure the OS is backing the allocation with actual RAM (or swap). This is also why it is slower than malloc (not only does it have to zero it, the OS must also find a suitable memory area by possibly swapping out other processes)
See for instance this SO question for further discussion about the behavior of malloc