C++ Riddle - crash in sort - Mar-16, 2022

The following code crashes in both GCC and Clang (with both libc++ and libstdc++):

int main() {
    struct Point { long x, y; };
    std::vector<Point> points;
    for(long i = 0; i < 1000; ++ i) {
        points.push_back({rand() % 100, rand() % 100});
    }
    std::sort(std::begin(points), std::end(points),
              [](auto a, auto b) { return a.x <= b.x; });
    for(auto p: points) {
        std::cout << '{' << p.x << ", " << p.y << '}' << std::endl;
    }
}

Propose the smallest fix to make the code legit (avoiding the crash) and explain your suggestion.

dont know exactly why yet, but changing <= to < fix the asan issue. still thinking about it …

ok. found something

Yes Kobi - you got it right by yourself, and you also got to the exact SO question that inspired me with this riddle. Well done!

The fix is to change <= to < in given predicate to std::sort
As std::sort expects a valid comparison function object which returns ​true if the first argument is less than (i.e. is ordered before ) the second.

Welcome nirli.
Yes, that’s correct!