https://gcc.gnu.org/bugzilla/show_bug.cgi?id=122224
--- Comment #10 from GCC Commits <cvs-commit at gcc dot gnu.org> --- The master branch has been updated by Jonathan Wakely <[email protected]>: https://gcc.gnu.org/g:02797a4eeb9453a1c640171d00e52837c5b3de42 commit r16-4564-g02797a4eeb9453a1c640171d00e52837c5b3de42 Author: Jonathan Wakely <[email protected]> Date: Tue Oct 21 17:06:49 2025 +0100 libstdc++: Avoid incrementing input iterators with std::prev [PR122224] As explained in PR libstdc++/122224 we do not make it ill-formed to call std::prev with a non-Cpp17BidirectionalIterator. Instead we just use a runtime assertion to check the std::advance precondition that the distance is not negative. This allows us to support std::prev on types which model the C++20 std::bidirectional_iterator concept but do not meet the Cpp17BidirectionalIterator requirements, e.g. iota_view's iterators. It also allows us to support std::prev(iter, -1) which is admittedly weird, but there's no reason it shouldn't be equivalent to std::next(iter), which is perfectly fine to use on non-bidirectional iterators. In other words, "reverse decrementing" is valid for non-bidirectional iterators. However, the current implementation of std::advance for non-bidirectional iterators uses a loop that does `while (n--) ++i;` which assumes that n is not negative and so will eventually reach zero. When the assertion for the precondition is not enabled, incrementing the iterator while n is non-zero means that using std::prev(iter) or std::next(iter, -1) on a non-bidirectional iterator will keep incrementing the iterator until n reaches INT_MIN, overflows, and then keeps decrementing until it eventually reaches zero. Incrementing most iterators that many times will cause memory safety errors long before the integer reaches zero and terminates the loop. This commit changes the loop to use `while (n-- > 0)` which means that the loop doesn't execute at all if a negative n is used. We still consider such calls to be erroneous, but when the precondition isn't checked by an assertion, the function now has no effects. The undefined behaviour resulting from incrementing the iterator is prevented. libstdc++-v3/ChangeLog: PR libstdc++/122224 * include/bits/stl_iterator_base_funcs.h (prev): Compare distance as n > 0 instead of n != 0. * testsuite/24_iterators/range_operations/122224.cc: New test. Reviewed-by: Tomasz KamiÅski <[email protected]>
