What's the difference between calloc & malloc followed by a memset?

Possible Duplicate:
c difference between malloc and calloc
why malloc+memset slower than calloc?

What's the difference between calloc & malloc followed by a memset? If I replace all calls to calloc with a malloc followed by a memset, will it be the same?

If that is the case, then why are two functions malloc & calloc seperately provided?


While calloc() always initialises the memory area with zeroes ( '' ), the memset() call allows you to choose which bytes to fill the memory with.

In terms of speed, calloc() is likely to be faster than malloc() + memset() if memory needs to be zeroed out; malloc() returns uninitialised memory faster but it still requires an additional call to memset() .

Basically, if you want to zero out the memory, use calloc() ; if you want to leave it uninitialised, use malloc() .


One important difference is that I expect calloc(nmemb, size) to return NULL if nmemb * size overflows. If you instead use malloc(nmemb * size) , multiplicative overflow can cause you to request a smaller buffer than you expected (which could lead to security problems later). Therefore if you're planning to replace calloc calls with malloc ones, some care is necessary.

链接地址: http://www.djcxy.com/p/28454.html

上一篇: Malloc或Calloc以及何时

下一篇: calloc和malloc跟memset有什么区别?