It’s very bothersome for me to write calloc(1, sizeof(MyStruct)) all the time. I don’t want to use an idea like wrapping this method and etc. I mean I want to know what two parameters gives me? If it gives something, why doesn’t mallochave two parameters too?
By the way, I searched for an answer to this question but I didn’t find a really good answer. Those answers was that calloc can allocate larger blocks than malloc can and etc.
I saw another answer that calloc allocates an array. With malloc I can multiply and I’ll get an array and I can use it without 1, at the start.
Historical reasons.
At the time of when
callocwas introduced, themallocfunction didn’t exist and thecallocfunction would provide the correct alignment for one element object.When
mallocwas introduced afterwards, it was decided the memory returned would be properly aligned for any use (which costs more memory) and so only one parameter was necessary. The API forcallocwas not changed butcallocnow also returns memory properly aligned for any use.EDIT:
See the discussion in the comments and the interesting input from @JimBalter.
My first statement regarding the introduction of
mallocandcallocmay be totally wrong.Also the real reasons could also be well unrelated to alignment. C history has been changed a lot by compiler implementers.
mallocandcalloccould come from different groups / compilers implementers and this would explain the API difference. And I actually favor this explanation as the real reason.