https://gcc.gnu.org/bugzilla/show_bug.cgi?id=77550
Bug ID: 77550 Summary: std::deque with -O3 has infinite std::distance Product: gcc Version: 6.2.0 Status: UNCONFIRMED Severity: critical Priority: P3 Component: c++ Assignee: unassigned at gcc dot gnu.org Reporter: dan.cooke89 at gmail dot com Target Milestone: --- The following program, compiled with -O3, never returns: #include <string> #include <deque> #include <iterator> #include <iostream> #include <boost/iterator/filter_iterator.hpp> struct Foo { std::string bar, s = ""; char a = '\0'; }; int main() { const std::deque<Foo> foos(14, {""}); const std::string test {}; const auto p = [test] (const auto& foo) { return foo.bar == test; }; using boost::make_filter_iterator; const auto begin = make_filter_iterator(p, std::cbegin(foos), std::cend(foos)); const auto end = make_filter_iterator(p, std::cend(foos), std::cend(foos)); std::cout << std::distance(begin, end) << std::endl; } Observations: - GCC with optimisations -O2 or less returns as expected. - Clang (3.8) returns the correct answer with any optimisation level. - Changing std::deque to std::vector or std::list results in expected behaviour. - The 14 is critical; anything less and the problem disappears. - The sizeof(Foo) is important; removing s or a makes the problem go away. - Capturing test by reference, or just comparing to a constant expression (e.g. foo.bar == " ") results in normal behaviour. - There are no compiler warnings (with -Wall -Wextra -pedantic). - Valgrind reports no errors. - Use fsanitize=undefined and the problem goes away. From: http://stackoverflow.com/q/39424753/2970186