From mboxrd@z Thu Jan 1 00:00:00 1970 Return-Path: Received: by sourceware.org (Postfix, from userid 2181) id D579A3857820; Fri, 1 Oct 2021 19:38:23 +0000 (GMT) DKIM-Filter: OpenDKIM Filter v2.11.0 sourceware.org D579A3857820 MIME-Version: 1.0 Content-Transfer-Encoding: 7bit Content-Type: text/plain; charset="utf-8" From: Jonathan Wakely To: gcc-cvs@gcc.gnu.org, libstdc++-cvs@gcc.gnu.org Subject: [gcc r12-4062] libstdc++: Do not allocate a zero-size vector [PR 100153] X-Act-Checkin: gcc X-Git-Author: Jonathan Wakely X-Git-Refname: refs/heads/master X-Git-Oldrev: 741c7350c08b0884689466867b6c9e711c7b109e X-Git-Newrev: 681707ec28d56494fa61a80c62500724d55f8586 Message-Id: <20211001193823.D579A3857820@sourceware.org> Date: Fri, 1 Oct 2021 19:38:23 +0000 (GMT) X-BeenThere: libstdc++-cvs@gcc.gnu.org X-Mailman-Version: 2.1.29 Precedence: list List-Id: Libstdc++-cvs mailing list List-Unsubscribe: , List-Archive: List-Help: List-Subscribe: , X-List-Received-Date: Fri, 01 Oct 2021 19:38:24 -0000 https://gcc.gnu.org/g:681707ec28d56494fa61a80c62500724d55f8586 commit r12-4062-g681707ec28d56494fa61a80c62500724d55f8586 Author: Jonathan Wakely Date: Tue Apr 20 16:16:13 2021 +0100 libstdc++: Do not allocate a zero-size vector [PR 100153] The vector::shrink_to_fit() implementation will allocate new storage even if the vector is empty. That then leads to the end-of-storage pointer being non-null and equal to the _M_start._M_p pointer, which means that _M_end_addr() has undefined behaviour. The fix is to stop doing a useless zero-sized allocation in shrink_to_fit(), so that _M_start._M_p and _M_end_of_storage are both null after an empty vector shrinks. Signed-off-by: Jonathan Wakely libstdc++-v3/ChangeLog: PR libstdc++/100153 * include/bits/vector.tcc (vector::_M_shrink_to_fit()): When size() is zero just deallocate and reset. Diff: --- libstdc++-v3/include/bits/vector.tcc | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/libstdc++-v3/include/bits/vector.tcc b/libstdc++-v3/include/bits/vector.tcc index caee5cbfc2f..16366e03c86 100644 --- a/libstdc++-v3/include/bits/vector.tcc +++ b/libstdc++-v3/include/bits/vector.tcc @@ -944,7 +944,13 @@ _GLIBCXX_BEGIN_NAMESPACE_CONTAINER return false; __try { - _M_reallocate(size()); + if (size_type __n = size()) + _M_reallocate(__n); + else + { + this->_M_deallocate(); + this->_M_impl._M_reset(); + } return true; } __catch(...)