Skip to content

libc++ hardening mode doesn't detect invalid std::vector iterator #128627

Open
@thesamesam

Description

@thesamesam

Noticed when reading https://jacko.io/smart_pointers.html.

libc++'s hardening mode doesn't detect the following invalid iterator, even with -D_LIBCPP_HARDENING_MODE=_LIBCPP_HARDENING_MODE_DEBUG, while -D_GLIBCXX_DEBUG (though not -D_GLIBCXX_ASSERTIONS does):

#include <vector>

int main() {
    std::vector<int> my_vector = {1, 2, 3};
    for (auto element : my_vector) {
        if (element == 2) {
            my_vector.push_back(4);
            /* The next loop iteration reads a dangling pointer. */
        }
    }
}

With -D_GLIBCXX_DEBUG, we get:

/opt/compiler-explorer/gcc-snapshot/lib/gcc/x86_64-linux-gnu/15.0.1/../../../../include/c++/15.0.1/debug/safe_iterator.h:394:
In function:
    _Safe_iterator<_Iterator, _Sequence, _Category> &
    gnu_debug::_Safe_iterator<gnu_cxx::normal_iterator<int *, std::
    vector<int>>, std::vector<int>, std::forward_iterator_tag>::operator++() 
    [_Iterator = gnu_cxx::normal_iterator<int *, std::vector<int>>, 
    _Sequence = std::vector<int>, _Category = std::forward_iterator_tag]

Error: attempt to increment a singular iterator.

Objects involved in the operation:
    iterator "this" @ 0x7ffc6fd16ef0 {
      type = gnu_cxx::normal_iterator<int*, std::vector<int, std::allocator<int> > > (mutable iterator);
      state = singular;
      references sequence with type 'std::debug::vector<int, std::allocator<int> >' @ 0x7ffc6fd16e90
    }

godbolt: https://godbolt.org/z/jKaYPY3vb

Metadata

Metadata

Assignees

No one assigned

    Labels

    hardeningIssues related to the hardening effortlibc++libc++ C++ Standard Library. Not GNU libstdc++. Not libc++abi.questionA question, not bug report. Check out https://llvm.org/docs/GettingInvolved.html instead!

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions