Bug 21404

Summary: wrong code for array copy in while loop
Product: gcc Reporter: Janis Johnson <janis>
Component: rtl-optimizationAssignee: Not yet assigned to anyone <unassigned>
Status: RESOLVED DUPLICATE    
Severity: normal CC: gcc-bugs
Priority: P2    
Version: 3.4.4   
Target Milestone: ---   
Host: Target:
Build: Known to work:
Known to fail: Last reconfirmed:

Description Janis Johnson 2005-05-05 17:10:33 UTC
This test case fails for GCC 3.3.x and GCC 3.4.x at any level of optimization
other than -O0:

extern void abort (void);
char buffer[20];
                                                                                
void foo (char *p, const char *q)
{
  int i = 0;
  while (q[i])
    p[i] = q[i++];
}
                                                                                
int
main ()
{
  foo (buffer, "howdy");
  if (buffer[0] != 'h')
    abort ();
  return 0;
}

I've tried it on powerpc64-linux and i686-linux and it fails on both.  It
doesn't fail with Red Hat's GCC 3.2.2-5 compiler (I don't have an FSF 3.2
compiler built anywhere), and doesn't fail with GCC 4.0.0 or GCC mainline.
Comment 1 Janis Johnson 2005-05-05 17:49:56 UTC
A workaround is to replace the body of the loop with:

{
  p[i] = q[i];
  i++;
}
Comment 2 Andrew Pinski 2005-05-05 18:12:12 UTC
This is invalid, there is no sequence point between the access of i and the increment of i so either can 
be first.

With -W -Wall we get a warning:
t.c:8: warning: operation on `i' may be undefined


*** This bug has been marked as a duplicate of 11751 ***