Skip to content

Instantly share code, notes, and snippets.

@sknjpn
Created August 21, 2022 03:24
Show Gist options
  • Save sknjpn/0fa72ebf53b1f4dfa5ca4288653f40e5 to your computer and use it in GitHub Desktop.
Save sknjpn/0fa72ebf53b1f4dfa5ca4288653f40e5 to your computer and use it in GitHub Desktop.
sort segmentation fault
#include <iostream>
#include <vector>
#include <algorithm>
// gcc version 11.2.0 (Ubuntu 11.2.0-19ubuntu1)
int main()
{
const std::vector<int> v = { 1, 4, 2, 5, 5, 2, 3, 5, 2, 3, 4, 6, 3, 2, 5, 1, 2, 3, 4, 5, 6, 5, 6 };
std::vector<const int*> vp(v.size());
for (int i = 0; i < v.size(); ++i) vp[i] = &v[i];
std::sort(vp.begin(), vp.end(), [](const int* a, const int* b) {
// Segmentation fault (core dumped)
return *a <= *b;
// 1, 1, 2, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 5, 5, 5, 5, 5, 5, 6, 6, 6,
//return *a < *b;
});
std::for_each(vp.begin(), vp.end(), [](const int* x) { std::cout << *x << ", "; });
std::cout << std::endl;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment