Why does calloc require two parameters and malloc just one?

前端 未结 5 1897
礼貌的吻别
礼貌的吻别 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:12

    The only reason I could come up with is that

    int *foo = calloc(42, sizeof *foo);
    

    is one character shorter than

    int *foo = malloc(42 * sizeof *foo);
    

    The real reason is apparently lost to the millennia centuries decades of C history and needs a programming language archaeologist to unearth, but might be related to the following fact:

    In contrast to malloc() - which needs to return a memory block aligned in accordance to the full block size - when using calloc() as intended, the memory block would only need to be aligned in accordance to the size passed as second argument. However, the C standard forbids this optimization in conforming implementations.

提交回复
热议问题