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

            Bug ID: 85902
           Summary: -Wstringop-truncation false-positive
           Product: gcc
           Version: 8.1.1
            Status: UNCONFIRMED
          Severity: normal
          Priority: P3
         Component: c
          Assignee: unassigned at gcc dot gnu.org
          Reporter: igor.chorazewicz at intel dot com
  Target Milestone: ---

Observed in fedora 28 - gcc 8.1.1 20180502 (Red Hat 8.1.1-1).

Consider the following code:

int main(int argc, char *argv[])
{
        char dst[10];

        strncpy(dst, argv[0], sizeof(dst));
        if (dst[sizeof(dst) - 1] == '\0')
                printf("%s\n", dst);

        return 0;
}

When compiled with '-Wall -O2' gcc gives following warning:
warning: 'strncpy' specified bound 10 equals destination size
[-Wstringop-truncation]

I think this code handles truncation correctly and gcc should not emit this
warning.
Warning persists even if we change the code to the following (which makes
buffer overflow impossible):

int main(int argc, char *argv[])
{
        char dst[10];

        strncpy(dst, argv[0], sizeof(dst));
        if (dst[sizeof(dst) - 1] == '\0')
                printf("%s\n", dst);
        else
                dst[sizeof(dst) - 1] = '\0';

        return 0;
}

In my project, this warning is triggered from following function,
which is attempt to implement safer strcpy:

static inline int
util_safe_strcpy(char *dst, const char *src, size_t max_length)
{
        if (max_length == 0)
                return -1;

        strncpy(dst, src, max_length);

        return dst[max_length - 1] == '\0' ? 0 : -1;
}

Moreover -Wstringop-truncation is not documented to be in -Wall:
https://gcc.gnu.org/onlinedocs/gcc/Warning-Options.html

Reply via email to