[cfe-dev] clang++: Handling of division by zero in array bounds
David Chisnall via cfe-dev
cfe-dev at lists.llvm.org
Wed Nov 9 02:06:40 PST 2016
On 9 Nov 2016, at 07:55, Stephan Bergmann via cfe-dev <cfe-dev at lists.llvm.org> wrote:
>
> What I observe with various versions of Clang:
>
>> $ cat test.cc
>> #include <iostream>
>> int main() {
>> char a[1/0];
>> std::cout << sizeof a << '\n';
>> }
>>
>> $ clang++ -Weverything test.cc
>> test.cc:3:11: warning: variable length arrays are a C99 feature
>> [-Wvla-extension]
>> char a[1/0];
>> ^
>> test.cc:3:11: warning: variable length array used [-Wvla]
>> 2 warnings generated.
>>
>> $ ./a.out
>> 0
>
> Is there a specific reason to not emit a warning/error about the undefined behavior in evaluating the constant bounds expression, 1/0?
I believe that the issue here is that 1/0 is *not* a constant expression, it is undefined behaviour (typically, run-time trap). We probably should have a special return value for attempting to evaluate something that should be an ICE and finding that the result is undefined, which would allow this to become a more helpful error along the lines of ‘array length is an undefined value, this will abort at run time’.
Currently, I believe that the undefined value is simply marked as something that can not be evaluated at compile time and so this is equivalent to:
int foo(int d)
{
char a[1/d];
std::cout << sizeof a << '\n';
}
This is valid code when d > 0, but if d == 0 it will likely trap.
David
More information about the cfe-dev
mailing list