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?
calloc() versus malloc() in CIt works similar to the malloc() but it allocate the multiple blocks of memory each of same size. Here is the syntax of calloc() in C language, void *calloc(size_t number, size_t size); Here, number − The number of elements of array to be allocated.
The malloc() and realloc() functions are part of dynamic memory; malloc() is used for the memory allocation and realloc() is used for the reallocation of the memory.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With