https://gcc.gnu.org/bugzilla/show_bug.cgi?id=103215
--- Comment #4 from Sergei Trofimovich <slyfox at gcc dot gnu.org> --- Created attachment 51792 --> https://gcc.gnu.org/bugzilla/attachment.cgi?id=51792&action=edit gdb-bug.cc Found similar bug in gdb/c++ at gdb/language.c. It might have slightly better loop structure. As a downside it relies on very complex std::sort definition. Extracted example: #include <algorithm> enum language_t { language_unknown, language_auto, language_foo, nr_languages }; extern const language_t languages_[nr_languages] /* = { auto, foo, unk } */; bool lc (language_t, language_t); const language_t* add_set_language_command () { language_t *ls = new language_t[nr_languages]; // pull auto, unk in front. sort the rest language_t* ls_p = ls; *ls_p++ = language_auto; *ls_p++ = language_unknown; language_t* sort_begin = ls_p; for (const auto lang : languages_) { // already present if (lang == language_auto || lang == language_unknown) continue; *ls_p++ = lang; } std::sort (sort_begin, ls_p, lc); return ls; } $ ./gcc12/bin/g++-12.0.0 -O2 gdb-bug.cc -Werror=array-bounds In file included from /...-gcc-12.0.0/include/c++/12.0.0/algorithm:61, from gdb-bug.cc:1: In function 'void std::__final_insertion_sort(_RandomAccessIterator, _RandomAccessIterator, _Compare) [with _RandomAccessIterator = language_t*; _Compare = __gnu_cxx::__ops::_Iter_comp_iter<bool (*)(language_t, language_t)>]', inlined from 'void std::__sort(_RandomAccessIterator, _RandomAccessIterator, _Compare) [with _RandomAccessIterator = language_t*; _Compare = __gnu_cxx::__ops::_Iter_comp_iter<bool (*)(language_t, language_t)>]' at /...-gcc-12.0.0/include/c++/12.0.0/bits/stl_algo.h:1940:31, inlined from 'void std::sort(_RAIter, _RAIter, _Compare) [with _RAIter = language_t*; _Compare = bool (*)(language_t, language_t)]' at /nix/store/kckkq6280kixj8wxg4d0ks9lck8nai73-gcc-12.0.0/include/c++/12.0.0/bits/stl_algo.h:4853:18, inlined from 'const language_t* add_set_language_command()' at gdb-bug.cc:28:19: /...-gcc-12.0.0/include/c++/12.0.0/bits/stl_algo.h:1849:32: error: array subscript 18 is outside array bounds of 'language_t [3]' [-Werror=array-bounds] 1849 | std::__insertion_sort(__first, __first + int(_S_threshold), __comp); | ~~~~~~~~~~~~~~~~~~~~~^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ gdb-bug.cc: In function 'const language_t* add_set_language_command()': gdb-bug.cc:12:53: note: at offset 72 into object of size 12 allocated by 'operator new []' 12 | language_t *ls = new language_t[nr_languages]; | ^ cc1plus: some warnings being treated as errors