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

            Bug ID: 100153
           Summary: Undefined behavior in stl_bvector.h
           Product: gcc
           Version: 12.0
            Status: UNCONFIRMED
          Severity: normal
          Priority: P3
         Component: libstdc++
          Assignee: unassigned at gcc dot gnu.org
          Reporter: hewillk at gmail dot com
  Target Milestone: ---

stl_bvector.h#L505:

  _Bit_type*
  _M_end_addr() const _GLIBCXX_NOEXCEPT
  {
    if (this->_M_end_of_storage)
      return std::__addressof(this->_M_end_of_storage[-1]) + 1;
    return 0;
  }

This one will cause UB if _M_end_of_storage is not nullptr and
_M_end_of_storage is equal to _M_start._M_p.

Consider (https://godbolt.org/z/vvrG6KcWP):

  std::vector<bool> bv{true, false, true};
  bv.clear();
  bv.shrink_to_fit();
  bv.capacity();

When shrink_to_fit() ends, _M_end_of_storage will be equal to _M_start._M_p and
not nullptr. In capacity():

  size_type
  capacity() const _GLIBCXX_NOEXCEPT
  { return size_type(const_iterator(this->_M_impl._M_end_addr(), 0)
    - begin()); }

we will call _M_end_addr() and perform illegal dereference which cause UB, same
with push_back(), insert() and flip().

Reply via email to