https://gcc.gnu.org/bugzilla/show_bug.cgi?id=115056
Bug ID: 115056 Summary: Miscompilation triggering -Wstringop-overflow and -Warray-bounds warning when -O2 or higher Product: gcc Version: 14.1.1 Status: UNCONFIRMED Severity: normal Priority: P3 Component: rtl-optimization Assignee: unassigned at gcc dot gnu.org Reporter: weilercdale at gmail dot com Target Milestone: --- I've isolated what appears to be an unsound __builtin_memset optimization applied by gcc 14.1.1 on a hash function in a cryptographic library where it writes one byte beyond the end of a buffer. The compiler thankfully reports two warnings when it happens. The isolated test case is small so I'll provide it inline #include <string.h> #include <stdio.h> typedef union { unsigned char as_bytes[64]; unsigned long long as_chunks[64 / sizeof(unsigned long long)]; } Block; int main(int argc, char **argv) { Block block; int i = strlen(argv[0]), j = 0; for (; j < i; j++) block.as_bytes[j] = argv[0][j]; while (++j & 7) block.as_bytes[j] = 0; if (j > 56) while (j < 64) block.as_bytes[j++] = 0; while (j < 56) block.as_bytes[j++] = 0; for (j = 0; j < 8; j++) printf("%d\n", (int)block.as_chunks[j]); } Compiling this with -O2 produces the following warning t.c: In function ‘main’: t.c:12:56: warning: ‘__builtin_memset’ writing 8 bytes into a region of size 7 overflows the destination [-Wstringop-overflow=] 12 | if (j > 56) while (j < 64) block.as_bytes[j++] = 0; | ~~~~~~~~~~~~~~~~~~~~^~~ t.c:8:15: note: at offset [57, 63] into destination object ‘block’ of size 64 8 | Block block; | ^~~~~ Compiling this with -O2 and -Wall produces the following warning t.c: In function ‘main’: t.c:12:56: warning: ‘__builtin_memset’ forming offset 64 is out of the bounds [0, 64] of object ‘block’ with type ‘Block’ [-Warray-bounds=] 12 | if (j > 56) while (j < 64) block.as_bytes[j++] = 0; | ~~~~~~~~~~~~~~~~~~~~^~~ t.c:8:15: note: ‘block’ declared here 8 | Block block; | ^~~~~