Difference between malloc and calloc?

后端 未结 14 1748
感情败类
感情败类 2020-11-22 03:40

What is the difference between doing:

ptr = (char **) malloc (MAXELEMS * sizeof(char *));

or:

ptr = (char **) calloc (MAXEL         


        
14条回答
  •  悲哀的现实
    2020-11-22 04:02

    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

提交回复
热议问题