Re: Allocations that overflow
"Angel Tsankov" wrote:
Hello,
According to the standard, what must the following function do
if it is passed std::numeric_limits<std::size_t>::max()?
struct S
{
char a[64]; // Any size greater than 1 would do.
};
S* allocate(std::size_t size)
{
return new S[size];
}
The real question is how the function will detect that the
resulting size is greater than
"std::numeric_limits<std::size_t>::max()"? According to the
standard (3.7.3.1/3) the only thing that allocation function is
allowed to do is to throw `std::bad_alloc' or return NULL (in case
that an empty exception-specification (throw()) variant is used).
I think that in practice the outcome is undefined. First of all,
it is unlikely that the system will be able to allocate such big
chunk of memory at all. And second, if some hypothetical system is
able to allocate this amount, then "size * sizeof(S)" value will
silently overflow `size_t' argument to allocation function and
resulting memory chunk will be less than required. So, when the
program will try to access an element of the array beyond
allocated space, then the program will exhibit undefined behavior,
i.e. some sort of access violation exception.
Alex