[PATCH] Fix -Wstringop-overflow warning in 23_containers/vector/types/1.cc PR109849

François Dumont frs.dumont@gmail.com
Mon Jun 3 17:46:08 GMT 2024


On 03/06/2024 18:20, Jonathan Wakely wrote:
> On Mon, 3 Jun 2024 at 05:56, François Dumont <frs.dumont@gmail.com> wrote:
>> I hadn't try to make my patch as limited as possible to fix the problem,
>> indeed.
>>
>>       libstdc++: Fix -Wstringop-overflow warning coming from std::vector
>> [PR109849]
>>
>>       libstdc++-v3/ChangeLog:
>>
>>               PR libstdc++/109849
>>               * include/bits/vector.tcc
>>               (std::vector<>::_M_range_insert(iterator, _FwdIt, _FwdIt,
>>               forward_iterator_tag)): Add __builtin_unreachable
>> expression to tell
>>               the compiler that the allocated buffer is large enough to
>> receive current
>>               elements plus the range to insert.
>>
>> Tested under Linux x64, ok to commit ?
> Does the !__builtin_constant_p(__len) in this version do anything?
>
> If it's a constant, then the compiler can already provide it's in
> range, so the __builtin_unreachable() is redundant, but doesn't do any
> harm.
>
Yes, it prevents some constexpr test failure because 
__builtin_unreachable is not a constexpr (at least not for some C++ 
Standard versions).

But it wasn't a nice way to avoid this regression. Here is another 
proposal that activate the __builtin_unreachable only for pre-c++11 
modes. C++03 had no problem neither but I haven't found any occurrence 
of __cplusplus checks against the C++03 version so I prefer not to add any.

     libstdc++: Fix -Wstringop-overflow warning coming from std::vector 
[PR109849]

     libstdc++-v3/ChangeLog:

             PR libstdc++/109849
             * include/bits/vector.tcc
             (std::vector<>::_M_range_insert(iterator, _FwdIt, _FwdIt,
             forward_iterator_tag))[__cplusplus < 2011103L]: Add 
__builtin_unreachable
             expression to tell the compiler that the allocated buffer 
is large enough to
             receive current elements plus the elements of the range to 
insert.

Ok to commit ?

François

-------------- next part --------------
diff --git a/libstdc++-v3/include/bits/vector.tcc b/libstdc++-v3/include/bits/vector.tcc
index 36b27dce7b9..c500aab9e56 100644
--- a/libstdc++-v3/include/bits/vector.tcc
+++ b/libstdc++-v3/include/bits/vector.tcc
@@ -933,6 +933,11 @@ _GLIBCXX_BEGIN_NAMESPACE_CONTAINER
 
 		const size_type __len =
 		  _M_check_len(__n, "vector::_M_range_insert");
+#if __cplusplus < 201103LL
+		if (__len < (__n + (__old_start - __old_finish)))
+		  __builtin_unreachable();
+#endif
+
 		pointer __new_start(this->_M_allocate(__len));
 		pointer __new_finish(__new_start);
 		__try


More information about the Gcc-patches mailing list