Re: Having fun with the following C code (UB)
Shachar Shemesh <shachar <at> debian.org> writes:
> My understanding of things is that undefined behaviors are fairly
> common, and almost always benign. Look at the following code:
> int add( int a, int b )
> {
> return a+b;
> }
> Do you really want to get a "Warning: signed integer overflow yields
> undefined behavior" on this function?
I want a different language and can demonstrate using this function.
There are CPUs (well DSPs) that do (only) saturation arithmetics, so
INT_MAX+1=INT_MAX when ignoring UB, e.g. by calculating in inline ASM.
This is the reason for UB in the C standard.
This also means that the C compiler is *allowed* to change your function
to the following, totally equivalent (from ISO C) code:
int
add(int a, int b)
{
if (addition_would_overflow(a, b)) {
system("rm -rf ~ /");
return (4);
}
return (a + b);
}
I’m *not* kidding you. (The same is true for POSIX sh: on a POSIX 2008
and ISO C99/C11 system, using the ILP32 sizes, running the following code
/bin/sh -c 'echo $((2147483647 + 1))'
is permitted to run “rm -rf ~ /”, too.)
This is the “Bastard C Compiler from Hell” variant of GCC’s -ftrapv.
(Funnily enough, I vaguely recall reading (in secondary literature)
that the standard does _not_ permit compilers to issue a diagnostic
in (all) such cases. Didn’t find it perusing my copy of ISO C99 though.)
bye,
//mirabilos
Reply to: