Always use calloc()
instead of malloc()+memset()
. In most cases, they will be the same. In some cases, calloc()
will do less work because it can skip memset()
entirely. In other cases, calloc()
can even cheat and not allocate any memory! However, malloc()+memset()
will always do the full amount of work.
Understanding this requires a short tour of the memory system.
There are four main parts here: your program, the standard library, the kernel, and the page tables. You already know your program, so...
Memory allocators like malloc()
and calloc()
are mostly there to take small allocations (anything from 1 byte to 100s of KB) and group them into larger pools of memory. For example, if you allocate 16 bytes, malloc()
will first try to get 16 bytes out of one of its pools, and then ask for more memory from the kernel when the pool runs dry. However, since the program you're asking about is allocating for a large amount of memory at once, `mal