Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I'm a beginner C programmer, and I assumed that this would be the case, but would like some affirmation if possible.

If they are the same, why not just take one argument instead?

like image 585
Ali Avatar asked Feb 01 '09 23:02

Ali


2 Answers

People mostly 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.

like image 175
paxdiablo Avatar answered Oct 04 '22 22:10

paxdiablo


To the excellent responses posted, I want to add one more point of difference between using calloc(nelem, elsize) versus malloc(nelem * elsize): quality implementations of calloc will ensure that if your nelem and elsize were big enough to cause an integer overflow when multiplied together, it will fail rather than cause an undersized allocation, as a naive malloc invocation would.

Just this feature alone would be enough for me to prefer calloc to malloc. Background reading.

like image 35
Chris Jester-Young Avatar answered Oct 04 '22 22:10

Chris Jester-Young