I am trying to work out some trivial c++ code snippets. Following c++ vector sort snippet either hangs or crashes with segfault (depending on number of elements in the vector)
On my mac, with 141 size, it hangs. With around 5000 size, it seg faults. On a linux, the below example segfaults.
I have tried both gcc and clang.
Is there something trivially wrong that I am doing here?
#include <stdio.h>
#include "iostream"
#include "vector"
#include "algorithm"
bool cmp_range(const std::pair<int, int> &a, const std::pair<int, int> &b) {
return a.first <= b.first;
}
int main() {
std::vector<std::pair<int, int>> ranges;
for (int i = 0; i < 10000; ++i) {
const int st = rand() % 1000;
const int en = st + rand() % 1000;
ranges.push_back(std::make_pair(st, en));
}
std::cout << "begin sorting: " << ranges.size() << std::endl;
std::sort(ranges.begin(), ranges.end(), cmp_range);
std::cout << "done sorting" << std::endl;
}
~$ g++ -std=c++11 test_sort.cpp && ./a.out
begin sorting: 10000
Segmentation fault
$ rm ./a.out ; clang++ -std=c++17 sort_test.cpp && ./a.out
begin sorting: 10000
Segmentation fault: 11