[Bug c/56463] infinite loop when having integer overflow in a simple accumulator

dominiq at lps dot ens.fr gcc-bugzilla@gcc.gnu.org
Tue Feb 26 18:42:00 GMT 2013


http://gcc.gnu.org/bugzilla/show_bug.cgi?id=56463

--- Comment #4 from Dominique d'Humieres <dominiq at lps dot ens.fr> 2013-02-26 18:41:56 UTC ---
> The compiler may assume that undefined behavior doesn't happen in the program.
> It is fine to have undefined behavior in code that will be never executed, but
> as soon as you hit it, the program can do anything.

IMO the anything should be based on the "quality of implementation".
The present behavior is

(1) inconsistent (see PR 54932), the following test

#include "stdio.h"
int main(void)
{
 int huge=2147483647;
 int i, j, k;
 int e;

 i=huge-10;
 j=0;
 k=0;
 do
   {
    j=j+1;
    k=k-1;
    e = (i == huge);
    i++;
    if (e) break;
   }
 while(1);
 printf("i=%d,  j=%d,  k=%d\n", i, j, k);

 return 0;
}

does not give an infinite loop, but skip the last iteration, while the
following test

#include "stdio.h"
int main(void)
{
 int huge=2147483647;
 int i, j, init;
 int e;

 init = 0;
 j = init;
 for(i=-(huge/2);i<=1+huge/2; i++)
   {
    e = (j == huge);
    j=j+1;
    if (e) break;
   }
 printf("i=%d,  j=%d\n", i, j);

 return 0;
}

gives an infinite loop when compiled with -O2 (but indeed works for any
init<0);

(2) easy to fool: PR 54932 again;

(3) nasty: an infinite loop can hardly be considered as an optimization and it
is done without warning.

And yes I know that a compiler can do anything with undefined behavior, even
issue a rm -rf * for the home directory (and there are standard fundamentalists
around who think that this is the only sensible behavior).



More information about the Gcc-bugs mailing list