[ACCEPTED]-sort function C++ segmentation fault-segmentation-fault

Accepted answer
Score: 66

In C++, your compare predicate must be a strict weak ordering. In 6 particular, compare(X,X) must return "false" for 5 any X. In your compare function, if both 4 pairs are identical, you hit the test (p1.first <= p2.first) , and 3 return true. Therefore, this compare predicate does 2 not impose a strict weak ordering, and the 1 result of passing it to sort is undefined.

Score: 3

Try using all the values from n = 32766 up to 32770. I 11 suspect you'll find that you are experiencing 10 some sort of overflow. This is because 2^15 9 (32768) is the biggest number that can be 8 represented using 16 bits (assuming you 7 also allow negative numbers). You will have 6 to use a different data type.


Get it to output 5 the vector's maxsize:

cout << p.max_size();

Let us know what that 4 does. All things being normal, I'd expect 3 it to be in the hundreds of millions (536870911 2 on my computer). But if it's more like 32768, then 1 that could be the problem.

Score: 1

Your overflow is possibly related to the 9 stack overrun due to passing two vectors 8 by value.

std::vector &vec - this is how you pass a vector 7 by reference.

Change bool compare(pair<int,int> p1,pair<int,int> p2) to bool compare(pair<int,int> &p1,pair<int,int> &p2)

If you think this 6 through, passing by reference will change 5 the size of stack data from size (2*n*4)*2 bytes 4 to 2x8 byte pointers

For n == 32767 you are reducing the 3 stack frame by approx (2*32767*4)*2

As a rule of thumb, pass 2 by reference unless your design requires 1 otherwise.

More Related questions