What if x*y doesn't fit in size_t? How does calloc()
handle this?
realloc()
and malloc()
are limited in that the size argument passed to them is limited to SIZE_MAX
. Not so with calloc()
A compliant C implementation is not required to limit calloc()
to allocating memory of only SIZE_MAX
. The following may work. An single type can have a maximum size of SIZE_MAX
and an array size can be as large as SIZE_MAX
SIZE_MAX-1 "bytes", yet iptr
below is not an array, but a pointer.
// Assume sizeof(double) == 8
double *iptr = calloc(SIZE_MAX, sizeof *iptr);
Re-allocating such large pointers is problematic as it requires using another call to calloc()
How to avoid overflow in realloc
?
OP's problem is not so much of what realloc()
can handle but of how code calculates the values passed to it may overflow.
To insure an unsigned type, like size_t
, does not overflow multiplication:
if (b && a > SIZE_MAX/b) Handle_Overflow();
prod = a*b;