https://gcc.gnu.org/bugzilla/show_bug.cgi?id=104966
--- Comment #8 from CVS Commits <cvs-commit at gcc dot gnu.org> --- The master branch has been updated by Jonathan Wakely <r...@gcc.gnu.org>: https://gcc.gnu.org/g:38ce4489635f2d65de965af3ec5d5c4adf7762d9 commit r12-7690-g38ce4489635f2d65de965af3ec5d5c4adf7762d9 Author: Jonathan Wakely <jwak...@redhat.com> Date: Thu Mar 17 13:33:07 2022 +0000 libstdc++: Rewrite __moneypunct_cache::_M_cache [PR104966] GCC thinks the following can lead to a buffer overflow when __ns.size() equals zero: const basic_string<_CharT>& __ns = __mp.negative_sign(); _M_negative_sign_size = __ns.size(); __negative_sign = new _CharT[_M_negative_sign_size]; __ns.copy(__negative_sign, _M_negative_sign_size); This happens because operator new might be replaced with something that writes to this->_M_negative_sign_size and so the basic_string::copy call could use a non-zero size to write to a zero-length buffer. The solution suggested by Richi is to cache the size in a local variable so that the compiler knows it won't be changed between the allocation and the copy. This commit goes further and rewrites the whole function to use RAII and delay all modifications of *this until after all allocations have succeeded. The RAII helper type caches the size and copies the string and owns the memory until told to release it. libstdc++-v3/ChangeLog: PR middle-end/104966 * include/bits/locale_facets_nonio.tcc (__moneypunct_cache::_M_cache): Replace try-catch with RAII and make all string copies before any stores to *this.