4

Following code gives "Bus error: 10", though it works perfectly when n is changed to 30. I REALLY do NOT see any single reason for that error. Why do you think this is happening?

#include <algorithm>
#include <cstdio>
#define MAX 100000
using namespace std;

struct suffix
{
    int cur;
};

suffix suffixes[MAX];

bool cmp(suffix a, suffix b)
{
    return (a.cur <= b.cur);
}

int main()
{
   int n = 1000;
   sort(suffixes,suffixes + n,cmp);
   return 0;
}
Transcendental
  • 929
  • 3
  • 8
  • 25

1 Answers1

4

Your compare function has a problem. It doesn't satisfy the requirements expected by std::sort. It needs to give a strict weak ordering, it must return false for equivalent elements. Try changing it to:

bool cmp(suffix a, suffix b)
{
    return (a.cur < b.cur); // note comparison is < instead of <=
}
Blastfurnace
  • 18,411
  • 56
  • 55
  • 70
  • It actually helps, thanks. But why do you think there is a threshold like 35? – Transcendental Dec 05 '15 at 06:43
  • @Enes: If you violate the algorithm's prerequisites it can lead to undefined behavior. Crashing is one possible result, the specific threshold isn't that important. – Blastfurnace Dec 05 '15 at 06:45
  • @Enes - FYI, if you used the Visual C++ compiler, this error would have been detected (in the debug runtime) and your program would have stopped with an assertion. The way Visual C++ checks this is to call your `cmp` function twice -- the first time with (a,b), and a second time with (b,a). If you gave an answer of `true` for both calls, the runtime asserts. The reason is that there is no way `a < b`, and at the same time `b < a`. – PaulMcKenzie Dec 05 '15 at 07:01