I am trying to sort a list (std::vector
) of 3D integer vectors (IntVec
). Somehow, std::sort
causes a Segmentation Fault in the operator<
of IntVec
. Here is my code:
#include <iostream>
#include <algorithm>
#include <vector>
#include <fstream>
struct IntVec
{
public:
long x;
long y;
long z; // Using ints does not cause the Segmentation Fault ?!
friend bool operator<(const IntVec &lhs, const IntVec &rhs)
{
return (lhs.z < rhs.z) || // Segmentation Fault happens here
((lhs.z == rhs.z) && (lhs.y < rhs.y))
|| ((lhs.y == rhs.y) && (lhs.x < rhs.x));
}
};
int main(void)
{
std::vector<IntVec> vec;
const int N = 2178;
std::ifstream s("res.txt");
for (int i = 0; i < N; i++)
{
IntVec t;
s >> t.x;
s >> t.y;
s >> t.z;
vec.push_back(t);
}
// Using vec.begin() and vec.end() does not change anything
std::sort(vec.data(), vec.data() + vec.size());
}
I can provide you the dataset; however, I wanted to see at first if I have some big conceptual mistake in my code or some error I do not see. I found that the problem is specific to that dataset. If I leave out one entry, the Segfault does not occur. I think that is quite weird, since such a mistake should be more obvious and related to memory management. Also notice that using integers for x
,y
and z
does not cause any problems.
Here is a godbolt version of the code.
Here is a related SO question. However, I think that my code does not have the same flaw that caused this error. I think my ordering relation is "strictly <".