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?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With