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

            Bug ID: 128919
           Summary: [12/13/14/15/16/17 Regression] wrong code: strlen pass
                    bounds a string stored through (char *)&struct by the
                    size of the struct's first member, so strncmp/strcmp
                    == 0 is folded to false
           Product: gcc
           Version: 17.0
            Status: UNCONFIRMED
          Severity: normal
          Priority: P3
         Component: c
          Assignee: unassigned at gcc dot gnu.org
          Reporter: 0599jiangyc at gmail dot com
  Target Milestone: ---

The following code:

```c
/* Godbolt: x86-64 gcc (trunk), flags: -O2
 gcc -O2 repro.c && ./a.out ; exit 1 = miscompiled (also -O3, -O3
-march=x86-64-v3; the strcmp form
   in agt-first-mb2.c also fails at -Os).  OK: -O0, -O1, -O2
-fno-optimize-strlen, GCC 11.4, clang.
   strncmp (p, "abcdefgh", 6) == 0 folded to 0.  */
#include <string.h>

struct S { char a[4]; char b[16]; } x;

__attribute__((noipa)) int
f (const char *s, int c)
{
  if (strlen (s) > 15)
    return -1;
  strcpy ((char *) &x, s);      /* the whole 20-byte object, not x.a */
  const char *p = c ? (char *) &x : "xy";
  return strncmp (p, "abcdefgh", 6) == 0;
}

int
main (void)
{
  if (f ("abcdefgh", 1) != 1)
    return 1;
  return 0;
}
```

Resulted in this output:
```
$ gcc -O2 repro.c && ./a.out
(exit 1: strncmp (p, "abcdefgh", 6) == 0 folded to 0)
(gcc -O0/-O1, -O2 -fno-optimize-strlen, GCC 11.4 and clang -O2 exit 0;
-fsanitize=address,undefined clean)
```

Trunk: https://godbolt.org/z/4P5j4dvnM (x86-64 gcc trunk, -O2, executed;
reproduces as of 2026-11-13; also GCC 14.2 and 15.2, not GCC 11.4)

Reply via email to