Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

std::sort function gives "Bus error: 10"

Tags:

c++

struct

stl

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;
}
like image 434
Transcendental Avatar asked Sep 14 '25 07:09

Transcendental


1 Answers

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 <=
}
like image 145
Blastfurnace Avatar answered Sep 17 '25 00:09

Blastfurnace