https://gcc.gnu.org/bugzilla/show_bug.cgi?id=81141
Bug ID: 81141 Summary: missing warning using sizeof a/sizeof *a with a zero-length array Product: gcc Version: 7.0 Status: UNCONFIRMED Severity: normal Priority: P3 Component: c Assignee: unassigned at gcc dot gnu.org Reporter: msebor at gcc dot gnu.org Target Milestone: --- GCC detects the common mistake of using the (sizeof P / sizeof *P) expression to attempt to compute the length of an array when P is a pointer. A similar mistake is using the same expression when P is a zero-length array because the result is zero, or a one-element array as the last element of a struct because such an array is often used as a substitute for a flexible array member. This is a enhancement request to add such a warning (either under -Wsizeof-pointer-div or under a new option). If this enhancement should be made available under a new warning option, since the programming error it detects boils down to essentially the same problem with the same conseequence, I would suggest to have the new option subsume the -Wsizeof-pointer-div functionality as well. A possible name for the new option might be -Wsizeof-division: "warn about uses of sizeof that appear as if they attempt to compute the size of an array but do not actually do so, or that may yield the wrong number of elements." $ cat x.c && gcc -O2 -S -Wall x.c struct S { char n, *s, a[0]; }; void h (void *d, const struct S *s) { __builtin_memcpy (d, s->s, sizeof s->s / sizeof *s->s); // warning (good) __builtin_memcpy (d, s->a, sizeof s->a / sizeof *s->a); // missing warning extern char a[0]; __builtin_memcpy (d, s->a, sizeof a / sizeof *a); // missing warning } x.c: In function ‘h’: x.c:5:42: warning: division ‘sizeof (char * const) / sizeof (char)’ does not compute the number of array elements [-Wsizeof-pointer-div] __builtin_memcpy (d, s->s, sizeof s->s / sizeof *s->s); // warning (good) ^