https://gcc.gnu.org/bugzilla/show_bug.cgi?id=106434

--- Comment #8 from Jonathan Wakely <redi at gcc dot gnu.org> ---
So initially iin.iter._M_current is indeed null, because unique.begin() returns
_M_start (which is null) when the vector is empty:

  std::insert_iterator iin(unique, unique.begin());

But when the vector is empty, this condition is always false:

      if (this->_M_impl._M_finish != this->_M_impl._M_end_of_storage)
        if (__position == end())

It's impossible for _M_start to be null unless _M_finish and _M_end_of_storage
are also null.

After the first insertion into the vector all three of _M_start, _M_finish and
_M_end_of_storage are non-null. But after the first insertion
iin.iter._M_current is also non-null.

So we need to add a hint so the compiler knows that the jump threaded
"__position is null but finish != end_of_storage" case is nonsense. It's not
_impossible_, because a dumb user could make it happen, but it violates the
function precondition so is UB.

i.e. this would take that code path:

std::vector<int> v{1,2,3}; // non-empty vector
std::vector<int>::const_iterator null;
v.insert(null, 1); // try to insert at invalid position

But that's UB.


This seems to work (the __glibcxx_assert isn't needed to stop the warning, but
might be a useful assertion).


--- a/libstdc++-v3/include/bits/vector.tcc
+++ b/libstdc++-v3/include/bits/vector.tcc
@@ -137,8 +137,14 @@ _GLIBCXX_BEGIN_NAMESPACE_CONTAINER
     insert(iterator __position, const value_type& __x)
 #endif
     {
+      __glibcxx_assert(capacity() == 0 || __position != const_iterator());
+
       const size_type __n = __position - begin();
       if (this->_M_impl._M_finish != this->_M_impl._M_end_of_storage)
+        {
+          if (__position == const_iterator())
+            __builtin_unreachable();
+
        if (__position == end())
          {
            _GLIBCXX_ASAN_ANNOTATE_GROW(1);
@@ -159,6 +165,7 @@ _GLIBCXX_BEGIN_NAMESPACE_CONTAINER
            _M_insert_aux(__position, __x);
 #endif
          }
+      }
       else
 #if __cplusplus >= 201103L
        _M_realloc_insert(begin() + (__position - cbegin()), __x);

Reply via email to