Why calloc takes two arguments while malloc only one?

时光毁灭记忆、已成空白 提交于 2019-11-27 04:42:41

问题


IMO one is enough, why does calloc require to split it into two arguments?


回答1:


I'd guess that this is probably history and predates the times where C had prototypes for functions. At these times without a prototype the arguments basically had to be int, the typedef size_t probably wasn't even yet invented. But then INTMAX is the largest chunk you could allocate with malloc and splitting it up in two just gives you more flexibility and allows you to allocate really large arrays. Even at that times there were methods to obtain large pages from the system that where zeroed out by default, so efficiency was not so much a problem with calloc than for malloc.

Nowadays, with size_t and the function prototype at hand, this is just a daily reminder of the rich history of C.




回答2:


The parameter names document it reasonably well:

void *malloc(size_t size);
void *calloc(size_t nelem, size_t elsize);

The latter form allows for neat allocating of arrays, by providing the number of elements and element size. The same behavior can be achieved with malloc, by multiplying.

However, calloc also initializes the allocated memory to 0. malloc does no init, so the value is undefined. malloc can be faster, in theory, due to not setting all the memory; this is only likely to be noted with large amounts.

In this question, it is suggested that calloc is clear-alloc and malloc is mem-alloc.



来源:https://stackoverflow.com/questions/7536413/why-calloc-takes-two-arguments-while-malloc-only-one

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!