user923005 said:
Relying on undocumented (at best) behavior seems a bit strange to me.
I guess that {for instance} passing two (size_t)-1 values into calloc()
will result in undefined behavior. I guess that calloc() could
conceivably be clever enough to catch it, but I am very sure that it
would not be portable.
C99 Final Draft says: "The calloc function allocates space for an array
of nmemb objects, each of whose size is size.The space is initialized
to all bits zero. " and later "The calloc function returns either a
null pointer or a pointer to the allocated space."
There is no mention there of any problems in the calculation of nmemb *
size. calloc should either allocate space for nmemb objects and return
a pointer to those objects, or return a null pointer. That
specification is quite clear, and I wouldn't accept any excuses if it
is not followed. If I pass for example nmemb = 0x10001, and size =
0x10001, and in the C implementation that I use 0x10001 * 0x10001 ==
0x20001 (which is quite common), then it should be obvious that
allocating 0x20001 bytes will not give enough space for 0x10001 objects
of 0x10001 bytes, and a calloc implementation doing this would be just
plain broken.
The spec says "nmemb objects, each of whose size is size", not "nmemb *
size bytes".
That said, I wouldn't be surprised by the occasional broken C library
implementation.