Search code examples
ccalloc

Is there any specific difference between calloc calls of equivalent length but different per-object size?


// Is

calloc(10, 5);

// exactly the same as 

calloc(50, 1);
calloc(25, 2);

etc. in all possible cases?


Solution

  • You can imagine that calloc(m, n) is 100% completely and totally equivalent to

    p = malloc(m * n);
    if(p) memset(p, 0, m*n);
    

    There are various questions that come up with respect to alignment, but the answer is "no, calloc doesn't do anything special -- that is, doesn't do anything different than plain malloc -- with respect to alignment".

    There are obviously problems if m*n is too big to allocate (or too big for type size_t to represent), but if you're trying to allocate that much, pretty much all bets are off. (But with that said, if m*n is large enough to make calloc fail, I suspect the results could be noticeably different, and might even be required by the Standard to be noticeably different, from the simplified code given here.)

    Finally, the zeroing done by calloc definitely is to all-bits-0, just like memset, which may have implications for initialized pointers or floating-point quantities on some architectures.

    See also the C FAQ list, question 7.31.