Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
291 views
in Technique[技术] by (71.8m points)

c - Why calloc wasn't intended to assign arbitrary values?

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...