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

            Bug ID: 97336
           Summary: False positive -Wstring-compare warning for strncmp()
           Product: gcc
           Version: 10.2.0
            Status: UNCONFIRMED
          Severity: normal
          Priority: P3
         Component: middle-end
          Assignee: unassigned at gcc dot gnu.org
          Reporter: franke at computer dot org
  Target Milestone: ---

Testcase:

$ uname -srvmo
CYGWIN_NT-10.0 3.1.7(0.340/5/3) 2020-08-22 17:48 x86_64 Cygwin

$ cygcheck -f /usr/bin/gcc
gcc-core-10.2.0-1

$ gcc --version
gcc (GCC) 10.2.0
...

$ cat test.c
int f(const char * p, int n)
{
  char buf[10] = {0, };
  int i;
  for (i = 0; i < (int)sizeof(buf)-1 && i < n; i++)
    buf[i] = p[i];
  if (!__builtin_strncmp(buf, "12345", 5)
      && (i == 5 || buf[5] == ' '))
    return 1;
  return 0;
}

$ gcc -Wstring-compare -O2 -c test.c
test.c: In function ‘f’:
test.c:7:8: warning: ‘__builtin_strncmp’ of strings of length 0 and 5 and bound
of 5 evaluates to nonzero [-Wstring-compare]
    7 |   if (!__builtin_strncmp(buf, "12345", 5)
      |        ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~


Apparently it is assumed that the copy loop is never executed.

Any of the following single line changes removes the warning:

 {
-  char buf[10] = {0, };
+  char buf[10]; __builtin_memset(buf, 0, sizeof(buf));
   int i;


   if (!__builtin_strncmp(buf, "12345", 5)
-      && (i == 5 || buf[5] == ' '))
+      && (buf[5] == ' ' || i == 5))
     return 1;


   if (!__builtin_strncmp(buf, "12345", 5)
-      && (i == 5 || buf[5] == ' '))
+      && (!buf[5] || buf[5] == ' '))
     return 1;

Reply via email to