The malloc()
function basically gets memory from two different places:
It requests memory directly from the operating system (the kernel). On Unix systems such as Linux and OS X, this is done with the mmap()
or sbrk()
system calls. Memory from the kernel is always zero-initialized to begin with.
It reuses memory that was freed earlier with free()
. This is always assumed to be full of junk.
Just use calloc()
. The calloc()
function knows which pool the memory came from. If it came from the OS, then it's already zero-initialized and you get zeroed memory for free. If the memory is from free()
, then calloc()
will zero it for you. See why malloc+memset is slower than calloc for more details.
Summary for the lazy: The calloc()
function already performs the optimization you are thinking of.