0

Consider the following code segment. It works fine when the vector is of a small size but crashes (segmentation fault) when it gets bigger than say 18 (in my example).

One of the reasons I think this happens is probably std::sort would have moved around objects creating new copies all over and when the vector get deallocated, it tries to free the original pointers.

If my hypothesis is correct, then what is the best way to sort such objects?

   class info {
       int idx, value, tsub;
       public:
       info(int a, int b, int c) : idx(a), value(b), tsub(c) {}
       static bool compareP(info i1, info i2) { return i1.tsub <= i2.tsub; }
   };

   class CustomClass {
       public:
       void MyFunc() {
           vector<info> data;
           for (int i = 0; i < 18; i++)
               data.push_back(info(0, 0, 0));
           sort(data.begin(), data.end(), info::compareP);
       }
   };

   int main() {
        CustomClass c;
        c.MyFunc();
   }

Thanks!

sud03r
  • 19,109
  • 16
  • 77
  • 96
  • 1
    Changing the condition to `<` instead of `<=` fixes it, so I'm thinking `sort` is constantly trying to move elements until it breaks, or makes some sort of assumption about `a < b && a > b` being false. – Weak to Enuma Elish Feb 21 '16 at 22:45
  • I disagree that this is a duplicate. The issue here is that the comparison function doesn't satisfy the requirements of the Compare concept, not that the asker doesn't know how to call `std::sort`. [This cppreference page](http://en.cppreference.com/w/cpp/concept/Compare) explains some requirements of the Compare type. – Weak to Enuma Elish Feb 21 '16 at 22:50
  • @JamesRoot that indeed fixes things! (About the duplicate) Exactly, I was writing the same! Even if the other question contains the answer, it is particularly hard to locate it. – sud03r Feb 21 '16 at 22:52
  • 2
    It is actually a duplicate of [this](http://stackoverflow.com/questions/18291620/why-will-stdsort-crash-if-the-comparison-function-is-not-as-operator) question! – Weak to Enuma Elish Feb 21 '16 at 22:59
  • std::sort() isn't stable, so < instead of <= doesn't matter. std::stable_sort() is stable, but it also requires <, but does this by swapping the arguments to a custom compare so the compare is later_object < earlier_object (if false earlier_object is moved, if true later_object is moved). Visual Studio debug build will check a custom compare to make sure it's < or >, and report an error if it's <= or >=. – rcgldr Feb 22 '16 at 00:09

0 Answers0