https://gcc.gnu.org/bugzilla/show_bug.cgi?id=128238

            Bug ID: 128238
           Summary: Wrong code due to strlen optimisation
           Product: gcc
           Version: 15.2.0
            Status: UNCONFIRMED
          Severity: normal
          Priority: P3
         Component: tree-optimization
          Assignee: unassigned at gcc dot gnu.org
          Reporter: will at benfold dot com
  Target Milestone: ---

The following code should exit with status 46, and indeed does so at -O0.  At
-O2, zero is returned instead, unless -fno-optimize-strlen is passed.

(I didn't include preprocessed source, but the behaviour is the same if
"string.h" is replaced by a forward declaration of strlen.)

----

#include "string.h"

#define LEN 46

int main ()
{
  char buf[LEN + 1];
  for (int i=0; i < LEN; ++i)
  {
    buf[i] = i ? 'y' : 'x';
  }
  buf[LEN] = 0;

  char buf2[LEN + 1];
  for (int i = 0; i < LEN + 1; ++i)
  {
    buf2[i] = buf[i];
  }

  char buf3[LEN + 1] = {0};
  for (int i = 0; i < LEN; ++i)
  {
    buf3[i] = buf2[i];
  }
  buf3[LEN] = 0;

  return strlen(buf3);
}

----

$ gcc -Wall -Wextra -O0 -o test strlen_bug.c && ./test; echo $?
46
$ gcc -Wall -Wextra -O2 -o test strlen_bug.c && ./test; echo $?
0
$ gcc -Wall -Wextra -O2 -fno-optimize-strlen -o test strlen_bug.c && ./test;
echo $?
46

----

Using GCC 15.2.0 on GNU/Linux, x86_64

I see the same behaviour with "x86-64 gcc 16.2" on Compiler Explorer.  Cannot
reproduce on CE using "x86_64 gcc trunk", so may have been fixed already.

Reply via email to