Why calloc wasn't intended to assign arbitrary values?

南笙酒味 提交于 2019-12-11 22:18:24

问题


As per Why malloc+memset is slower than calloc?

malloc+memset is slower than calloc under certain conditions.

Why wasn't calloc written in such a way that it can take an extra value argument ( like memset) to override default assignment by zero? What would have been the effect of that if it were done?


回答1:


These calloc or memset initializations operate on a byte level, so even memset with a value different from 0 is not that usefull. At least I don't remember having it used with different values. Mostly you allocate memory for a base type that is wider than char.

The other aspect is that calloc is initialization and not assignment. Platforms may have builtins that provide a fast initialization of all bytes to 0, you wouldn't capture this when passing an argument to initialize.

But probably the most important aspect is that this is history of C. These interfaces originate from the very beginning and are impossible to change.




回答2:


That's the way it's designed.

Mainly whenever you allocate memory, you are immediately going to assign values to it. Forcing calloc to initialize a particular is going to make unnecessary overhead. For example, you want to allocate an array of 1 million int's and assign values from 1 to 1 million.

If calloc() were to take an argument like:

int *ptr;
int initValue = 3;

ptr = calloc(NumItems, sizeof(int), initValue);

then calloc() is forced to initialize initValue to all the 1 million elements needlessly.



来源:https://stackoverflow.com/questions/16536738/why-calloc-wasnt-intended-to-assign-arbitrary-values

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