What is the difference between doing:
ptr = (char **) malloc (MAXELEMS * sizeof(char *));
or:
ptr = (char **) calloc (MAXEL
The documentation makes the calloc
look like malloc
, which just does zero-initialize the memory; this is not the primary difference! The idea of calloc
is to abstract copy-on-write semantics for memory allocation. When you allocate memory with calloc
it all maps to same physical page which is initialized to zero. When any of the pages of the allocated memory is written into a physical page is allocated. This is often used to make HUGE hash tables, for example since the parts of hash which are empty aren't backed by any extra memory (pages); they happily point to the single zero-initialized page, which can be even shared between processes.
Any write to virtual address is mapped to a page, if that page is the zero-page, another physical page is allocated, the zero page is copied there and the control flow is returned to the client process. This works same way memory mapped files, virtual memory, etc. work.. it uses paging.
Here is one optimization story about the topic: http://blogs.fau.de/hager/2007/05/08/benchmarking-fun-with-calloc-and-zero-pages/