https://gcc.gnu.org/bugzilla/show_bug.cgi?id=37475
--- Comment #18 from GCC Commits <cvs-commit at gcc dot gnu.org> --- The releases/gcc-14 branch has been updated by Jonathan Wakely <r...@gcc.gnu.org>: https://gcc.gnu.org/g:c4253d6a170f40725ce3a11ce7a3e236b6e4842f commit r14-10737-gc4253d6a170f40725ce3a11ce7a3e236b6e4842f Author: Jonathan Wakely <jwak...@redhat.com> Date: Tue Jun 11 16:45:43 2024 +0100 libstdc++: Fix std::codecvt<wchar_t, char, mbstate_t> for empty dest [PR37475] For the GNU locale model, codecvt::do_out and codecvt::do_in incorrectly return 'ok' when the destination range is empty. That happens because detecting incomplete output is done in the loop body, and the loop is never even entered if to == to_end. By restructuring the loop condition so that we check the output range separately, we can ensure that for a non-empty source range, we always enter the loop at least once, and detect if the destination range is too small. The loops also seem easier to reason about if we return immediately on any error, instead of checking the result twice on every iteration. We can use an RAII type to restore the locale before returning, which also simplifies all the other member functions. libstdc++-v3/ChangeLog: PR libstdc++/37475 * config/locale/gnu/codecvt_members.cc (Guard): New RAII type. (do_out, do_in): Return partial if the destination is empty but the source is not. Use Guard to restore locale on scope exit. Return immediately on any conversion error. (do_encoding, do_max_length, do_length): Use Guard. * testsuite/22_locale/codecvt/in/char/37475.cc: New test. * testsuite/22_locale/codecvt/in/wchar_t/37475.cc: New test. * testsuite/22_locale/codecvt/out/char/37475.cc: New test. * testsuite/22_locale/codecvt/out/wchar_t/37475.cc: New test. (cherry picked from commit 73ad57c244c283bf6da0c16630212f11b945eda5)