Is calloc(4, 6) the same as calloc(6, 4)?

There is no real difference between calloc(a, b) and calloc(b, a), despite – they both allocate the same amount of space and fill it appropriately. Alignment of elements within the block don’t enter into it, no padding is needed because you’re explicitly stating what the “size” of the thing is (any padding would be controlled by using sizeof in the second argument.

In terms of why you would use calloc rather than malloc, people often use allocation routines to allocate space for a set number of items, so calloc() allows that to be specified nicely. So, for example, if you want space for 100 integers or 20 of your own structure:

int *pInt = calloc (100, sizeof(int));
tMyStruct *pMyStruct = calloc (20, sizeof(tMyStruct));

This code actually looks slightly “nicer” than the equivalent malloc() calls:

int *pInt = malloc (100 * sizeof(int));
tMyStruct *pMyStruct = malloc (20 * sizeof(tMyStruct));

although, to seasoned C coders, there’s no real distinction (other than the zero initialization of course).

I have to say I have never used calloc in the wild, since I’m almost always creating a struct where zero’s don’t make sense. I prefer to initialize all the fields manually to ensure I get the values I want.

Leave a Comment