https://gcc.gnu.org/bugzilla/show_bug.cgi?id=104964
Bug ID: 104964 Summary: Wrong *** buffer overflow detected ***: terminated - acl Product: gcc Version: 12.0 Status: UNCONFIRMED Severity: normal Priority: P3 Component: tree-optimization Assignee: unassigned at gcc dot gnu.org Reporter: marxin at gcc dot gnu.org Target Milestone: --- The test-case is reduced from acl: $ cat x.c #include <stdio.h> #include <stdlib.h> #include <string.h> struct __string_ext { char s_str[0]; }; struct string_obj_tag { struct __string_ext i; }; typedef struct string_obj_tag string_obj; static void writeto(char *text_p, ssize_t size) { fprintf (stderr, "Write to: %p, size=%d\n", text_p, size); strncpy(text_p, "sparta", size); } int main() { ssize_t size = 30; string_obj *string_obj_p = (string_obj *)malloc (sizeof(string_obj) + size); fprintf (stderr, "allocated: %d B starting at %p\n", size, string_obj_p->i.s_str); writeto(string_obj_p->i.s_str, size); fprintf (stderr, "result STR(%p)=%s\n", string_obj_p->i.s_str, string_obj_p->i.s_str); return 0; } $ gcc x.c -D_FORTIFY_SOURCE=2 -O2 && ./a.out In file included from /usr/include/string.h:535, from x.c:3: In function ‘strncpy’, inlined from ‘writeto’ at x.c:19:3, inlined from ‘main’ at x.c:28:3: /usr/include/bits/string_fortified.h:95:10: warning: ‘__builtin___strncpy_chk’ writing 30 bytes into a region of size 0 overflows the destination [-Wstringop-overflow=] 95 | return __builtin___strncpy_chk (__dest, __src, __len, | ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 96 | __glibc_objsize (__dest)); | ~~~~~~~~~~~~~~~~~~~~~~~~~ allocated: 30 B starting at 0x4052a0 Write to: 0x4052a0, size=30 *** buffer overflow detected ***: terminated Aborted (core dumped) While clang is fine: $ clang x.c -D_FORTIFY_SOURCE=2 -O2 && ./a.out allocated: 30 B starting at 0x4052a0 Write to: 0x4052a0, size=30 result STR(0x4052a0)=sparta and ASAN,UBSAN as well: $ gcc-11 x.c -fsanitize=address,undefined && ./a.out allocated: 30 B starting at 0x603000000040 Write to: 0x603000000040, size=30 result STR(0x603000000040)=sparta I see the error happens also with older GCC compilers.