Re: Allocations that overflow
On Thu, 19 Jun 2008 00:24:57 +0300, "Angel Tsankov"
<fn42551@fmi.uni-sofia.bg> 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];
}
I can't find any prescribed behavior for this in the standard. However, VC9
does detect overflow for the multiplication of the count and object size.
Consider the following fragment:
int* f(size_t n)
{
return new int[n];
}
Compiled with cl -O2 -EHs -FAs -c a.cpp, I get:
?f@@YAPAHI@Z PROC ; f, COMDAT
; 3 : return new int[n];
mov eax, DWORD PTR _n$[esp-4]
xor ecx, ecx
mov edx, 4
mul edx
seto cl
neg ecx
or ecx, eax
mov DWORD PTR _n$[esp-4], ecx
jmp ??2@YAPAXI@Z ; operator new
?f@@YAPAHI@Z ENDP ; f
If overflow occurs, the argument to the operator new function will be
size_t(-1), i.e. all bits set, and operator new will detect this error.
(The seto/neg/or sequence does this.) Here's a full program to test it:
#include <stdio.h>
#include <stdexcept>
int* f(size_t n)
{
return new int[n];
}
int main()
{
try
{
f(size_t(-1));
}
catch (std::bad_alloc)
{
puts("1");
}
}
X>cl -O2 -EHs -W4 a.cpp
Microsoft (R) 32-bit C/C++ Optimizing Compiler Version 15.00.21022.08 for
80x86
Copyright (C) Microsoft Corporation. All rights reserved.
a.cpp
Microsoft (R) Incremental Linker Version 9.00.21022.08
Copyright (C) Microsoft Corporation. All rights reserved.
/out:a.exe
a.obj
X>a
1
--
Doug Harrison
Visual C++ MVP