I've spent quite a moment today trying to figure out why a super-simple C function, which reads a text file, doesn't work. I was able to make it work by swapping parameters in calloc
function:
Instead of:
calloc(1, size_of_the_memory_to_allocate)
I did:
calloc(size_of_the_memory_to_allocate, 1)
So instead of 1 element of size 20, I did 20 of size 1.
calloc(size, 1)
Is there any difference in the allocation?
EDIT2:
I guess I was not clear enough with the question, or it was misunderstood. The question was: "Why allocating pointer to pointer using calloc requires swapping arguments?". It wasn't about debugging the code, nor have I asked anyone to run it, it was about how calloc
works. The answer made by @chqrlie is exactly what I was looking for. I guess I have made a mistake of adding any code to the question, and readers concentrated on it, rather than on what I have asked for. So, here's an edit, and now chqrlie's answer fit perfectly. If this still is something that won't help other users, let's just delete the question and be done with it.
The prototypes for calloc
and fread
are:
void *calloc(size_t nmemb, size_t size);
size_t fread(void *ptr, size_t size, size_t nmemb, FILE *stream);
The order of arguments is indeed inconsistent between these standard C library functions. It is unfortunate but it has been like this for close to 40 years and cannot be changed now.
Note that if you swap the arguments in calloc
, you should get exactly the same behavior, but it is not the case for fread
that returns the number of elements completely read.
The behavior you describe in your updated question is highly surprising. Either there is something you are not telling us, or your C library implements a non standard constraint in calloc()
that ends up backfiring into a bug.
Note that calloc(nmemb, size)
cannot just call malloc(nmemb * size)
because of potential arithmetic overflow, which in the case of size_t
arguments is defined in the standard. For example calloc(-1, -1)
must fail, but instead would return malloc(1)
if naively calling malloc(nmemb * size)
. The test for this overflow might be buggy in such a way as to fail for calloc(1, size)
and not for calloc(size, 1)
with a large size
.
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