https://gcc.gnu.org/bugzilla/show_bug.cgi?id=106762
Bug ID: 106762 Summary: incorrect array bounds warning (-Warray-bounds) at -O2 on memset() Product: gcc Version: 11.2.0 Status: UNCONFIRMED Severity: normal Priority: P3 Component: c Assignee: unassigned at gcc dot gnu.org Reporter: para at tampabay dot rr.com Target Milestone: --- Created attachment 53517 --> https://gcc.gnu.org/bugzilla/attachment.cgi?id=53517&action=edit Minimized test case to reproduce the issue This bug also affects GCC 12.0.1. I have an inline function in a header file that does an array lookup, returning NULL if the index given is out of bounds in the array. The result is passed to another function to reset the structure. At -O2 this produces the following warning: bug.c:29:2: warning: ‘memset’ offset [0, 7] is out of the bounds [0, 0] [-Warray-bounds] 29 | memset(&obj->field1, 0xff, sizeof(obj->field1)); | ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ This does not happen at -O0 or -O1. It appears that some part of the compiler is incorrectly concluding that `obj` must be NULL. For now I am suppressing the warning by assigning a structure field before calling memset() to hint that the memset() is only reachable if the pointer is non-NULL. One of the necessary conditions for reproducing this bug is curiously that the field being memset() cannot be the first in the structure. In the attached code that reproduces the issue I am setting the array index `idx` to 0. The original code used a loop `for(idx = 0; idx < ary->objcnt; idx++)` such that the else case cannot be hit.