Why does calloc require two parameters and malloc just one?

前端 未结 5 1898
礼貌的吻别
礼貌的吻别 2020-12-09 09:39

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

5条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-09 10:00

    Historical reasons.

    At the time of when calloc was introduced, the malloc function didn't exist and the calloc function would provide the correct alignment for one element object.

    When malloc was 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 for calloc was not changed but calloc now 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 malloc and calloc may be totally wrong.

    Also the real reasons could also be well unrelated to alignment. C history has been changed a lot by compiler implementers. malloc and calloc could come from different groups / compilers implementers and this would explain the API difference. And I actually favor this explanation as the real reason.

提交回复
热议问题