http://gcc.gnu.org/bugzilla/show_bug.cgi?id=48985

           Summary: bogus buffer overflow warning and abort on static
                    flexible array member
           Product: gcc
           Version: 4.6.0
            Status: UNCONFIRMED
          Severity: normal
          Priority: P3
         Component: c
        AssignedTo: unassig...@gcc.gnu.org
        ReportedBy: mse...@gmail.com


GCC emits a bogus warning on the program below which then aborts at runtime.
Note that when the strncpy (s.c, "012", 4) call in line 24 is removed GCC
doesn't emit a warning but the program still aborts even though there is no
buffer overflow.

For statically allocated flexible array members I would expect
__builtin_object_size() to report the actual size of the array rather than
zero, analogously to the case when the array is allocated dynamically.

$ cat z.c && gcc -D_FORTIFY_SOURCE -O2 z.c && ./a.out
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

struct s {
    int i;
    char c[];
} s = { 1, "01234" };

size_t f (void) { return __builtin_object_size(&s.c, 0); }

size_t g (struct s *p) { return __builtin_object_size(p->c, 0); }

int main (void) {
    struct s *p;
    p = (struct s*)malloc (sizeof *p + 6);

    printf ("%zu %zu\n", f (), g (p));
    fflush (stdout);

    strncpy (p->c, "012", strlen(s.c));

    if (puts ("###"))
        strncpy (s.c, "012", 4);   /* line 24 */
    strncpy (s.c, "012", strlen(s.c) + 1);

    return 0;
}
In file included from /usr/include/string.h:642:0,
                 from z.c:3:
In function ‘strncpy’,
    inlined from ‘main’ at z.c:24:17:
/usr/include/bits/string3.h:121:3: warning: call to __builtin___strncpy_chk
will always overflow destination buffer [enabled by default]
0 6
###
*** buffer overflow detected ***: ./a.out terminated
...
Aborted (core dumped)

Reply via email to