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

            Bug ID: 90892
           Summary: [9/10 regression] -O2 miscompiles __builtin_strncmp
                    with string containing '\0'
           Product: gcc
           Version: 9.1.1
            Status: UNCONFIRMED
          Severity: normal
          Priority: P3
         Component: tree-optimization
          Assignee: unassigned at gcc dot gnu.org
          Reporter: romain.geissler at amadeus dot com
  Target Milestone: ---

Hi,

It looks like doing things like __builtin_strncmp(someString, "A\0", 2) does an
out of bound comparison (ie comparing 3 chars instead of 2), and leads to wrong
behavior. It happens with gcc 9.1.1 and apparently 10 as well (checked on
godbolt: https://godbolt.org/z/CDvkRs)

> cat test.c
volatile char a[3] = { 'A', '\0', 42 };

int main()
{
    char b[3] = {a[0], a[1], a[2]};

    return __builtin_strncmp(b, "A\0", 2);
}


> gcc -O2 -o test test.c
> ./test && echo 'OK!!!' || echo 'KO...'
KO...

I would expect that it always returns "OK!!!" no matter which optimization
level is used. -O0 and -O1 are working fine. gcc 8 is happy with this at all
optimization levels. I hope using strings like "A\0" is not UB.

Cheers,
Romain

Reply via email to