📜  calloc vs malloc - 任何代码示例

📅  最后修改于: 2022-03-11 14:59:52.308000             🧑  作者: Mango

代码示例1
malloc() allocates memory block of given size (in bytes) and returns a pointer to the beginning of the block. 
malloc() doesn’t initialize the allocated memory. 
If we try to access the content of memory block(before initializing) then we’ll get segmentation fault error(or maybe garbage values).

calloc() allocates the memory and also initializes the allocated memory block to zero. 
If we try to access the content of these blocks then we’ll get 0.

Note: It would be better to use malloc over calloc, unless we want the zero-initialization because malloc is faster than calloc. 
So if we just want to copy some stuff or do something that doesn’t require filling of the blocks with zeros, then malloc would be a better choice.