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

            Bug ID: 108154
           Summary: Inappropriate -Wstringop-overread in the C99 [static
                    n] func decl
           Product: gcc
           Version: 11.3.1
            Status: UNCONFIRMED
          Keywords: diagnostic
          Severity: normal
          Priority: P3
         Component: middle-end
          Assignee: unassigned at gcc dot gnu.org
          Reporter: roman.zilka at gmail dot com
  Target Milestone: ---
              Host: x86_64-pc-linux-gnu
            Target: x86_64-pc-linux-gnu
             Build: x86_64-pc-linux-gnu

Created attachment 54116
  --> https://gcc.gnu.org/bugzilla/attachment.cgi?id=54116&action=edit
gcc -v

GCC issues Wstringop-overread when a function declared with "buffer[static n]"
reads past the n-th item of the buffer.


$ cat test.c
#include <string.h>
void f(char s[static 1]) {
        ++s;
        if (strchr(s, 'a')) ++*s;
}
int main() {
        char s[10] = {0};
        f(s);
}

$ gcc -O1 test.c
test.c: In function ‘f’:
test.c:4:13: warning: ‘strchr’ reading 1 or more bytes from a region of size 0
[-Wstringop-overread]
    4 |         if (strchr(s, 'a')) ++*s;
      |             ^~~~~~~~~~~~~~
test.c:2:13: note: at offset 1 into source object ‘s’ of size [0, 1]
    2 | void f(char s[static 1]) {
      |        ~~~~~^~~~~~~~~~~


That may be a correct read, though, as 'n' is the size lower bound. Sure, it's
idiomatic to understand the phrase "the size of 'buffer' is at least 'n'" (as
C99 defines this type of declaration) as "this function operates on up to 'n'
items and doesn't care what's after that bound". This syntax is useful,
however, as "buffer[static 1]" to advertise to the compiler and the function
user that a non-NULL ptr must be passed.

I have a few functions in a sourcefile that handle 0-term. strings and make use
of that. The string length is not passed in another argument, so I can't use
"f(size_t n, char buffer[static n])". The amount of false-positive
Wstringop-overreads is so large it's not even helpful to use "pragma diagnostic
ignored" and I just disable the warning altogether, which is sub-ideal. As much
as I hate the syntax, after 23 years it looks like it's in the language to stay
and it's just too damn useful for documentation and code optimization (bug
102556). I'm actually surprised that so few people make use of it, although the
ugliness of it does provide a lead.

Please consider exempting this kind of declaration from Wstringop-overread.
Similar: bug 104854.

Reply via email to