https://gcc.gnu.org/bugzilla/show_bug.cgi?id=109727
Bug ID: 109727 Summary: [13/14 Regression] -Warray-bounds false positive with -fsanitize=undefined Product: gcc Version: 13.1.0 Status: UNCONFIRMED Keywords: diagnostic Severity: normal Priority: P3 Component: c++ Assignee: unassigned at gcc dot gnu.org Reporter: dani at danielbertalan dot dev Target Milestone: --- The following code results in a -Warray-bounds warning with GCC 13.1+ and -fsanitize=undefined. No diagnostics are produced by older compilers or if UBSan is not enabled. template <unsigned inline_capacity> struct ByteBuffer { static ByteBuffer create_uninitialized(); static void copy() { auto new_buf = create_uninitialized(); new_buf.data(); } char *data() { return m_inline ? m_inline_buffer : m_outline_buffer; } union { char m_inline_buffer[inline_capacity]; char *m_outline_buffer; }; bool m_inline; }; void test() { ByteBuffer<56> buf1; buf1.data(); ByteBuffer<2>::copy(); } Compile with g++ -O2 -Warray-bounds -fsanitize=undefined: In member function 'char* ByteBuffer<inline_capacity>::data() [with unsigned int inline_capacity = 56]', inlined from 'char* ByteBuffer<inline_capacity>::data() [with unsigned int inline_capacity = 2]' at <source>:7:9, inlined from 'static void ByteBuffer<inline_capacity>::copy() [with unsigned int inline_capacity = 2]' at <source>:5:19, inlined from 'void test()' at <source>:18:22: <source>:7:34: warning: array subscript 'ByteBuffer<56>[0]' is partly outside array bounds of 'ByteBuffer<2> [1]' [-Warray-bounds=] 7 | char *data() { return m_inline ? m_inline_buffer : m_outline_buffer; } | ~~~~~~~~~^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ <source>: In function 'void test()': <source>:4:12: note: object 'new_buf' of size 16 4 | auto new_buf = create_uninitialized(); | ^~~~~~~ It looks like something about the two SSO buffer lengths gets confused: the error trace incorrectly indicates that ByteBuffer<56>::data() is getting inlined into ByteBuffer<2>::data(). Removing either this template parameter, the m_outline_buffer union member, or calling ByteBuffer::copy with the same template parameter in test() fixes the diagnostic. https://godbolt.org/z/6rqEnhP6q