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

            Bug ID: 88059
           Summary: Spurious stringop-overflow warning with strlen, malloc
                    and strncpy
           Product: gcc
           Version: 8.2.0
            Status: UNCONFIRMED
          Severity: normal
          Priority: P3
         Component: middle-end
          Assignee: unassigned at gcc dot gnu.org
          Reporter: listes at defendingthemusic dot fr
  Target Milestone: ---

The following combination of `strlen`, `malloc` and `strncpy` results in a
spurious warning when compiling with optimisation (at least -O2):

```
$ cat bug.c

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

char* copy_name (const char* src)
{
        size_t len = strlen(src) + 1;
        char* dest = malloc(len);
        if (dest)
                strncpy(dest, src, len);
        return dest;
}

int main (void)
{
        const char* name = "Name";
        char* copy = copy_name(name);
        printf("%s\n", copy);
        return 0;
}

$ gcc -O2 bug.c

bug.c: In function ‘copy_name’:
bug.c:10:3: warning: ‘strncpy’ specified bound depends on the length of the
source argument [-Wstringop-overflow=]
   strncpy(dest, src, len);
   ^~~~~~~~~~~~~~~~~~~~~~~
bug.c:7:15: note: length computed here
  size_t len = strlen(src) + 1;
               ^~~~~~~~~~~

```
This is actually safe since the result of `strlen` is used for both `malloc`
and `strncpy`.

Reply via email to