Vishal
Vishal

Reputation: 33

Segmentation fault in sort function

I am working on a code that sorts a 2d vector based on it's first column, The code gives out a segmentation fault on the input

6
7 1 3 4 1 7 

Code:

#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
bool sortcol(const vector <int> v1,const vector <int> v2){
 return v1[0]<v2[0];
}
int main() {
int n;
cin>>n;
vector < vector<int> > v(n);
for(int i=0;i<n;i=i+1){
    vector <int> temp2;
    int temp;
    cin>>temp;
    temp2.push_back(temp);
    temp2.push_back(i);
    v.push_back(temp2);
}
sort(v.begin(),v.end(),sortcol);
return 0;
}

Upvotes: 0

Views: 682

Answers (3)

Jayaraj Balagopal
Jayaraj Balagopal

Reputation: 51

The problem is that you are trying to reserve the wrong way in this particular case. Use

    v.reserve(n);

instead.

Upvotes: 3

Slava
Slava

Reputation: 44238

Your comparator has 2 issues:

bool sortcol(const vector <int> v1,const vector <int> v2){
   return v1[0]<v2[0];
}
  • it does not check if vectors passed to it do have at least one element

  • you should pass vectors by const reference (this is not error, but can lead to bad performance issue)

So in your code:

vector < vector<int> > v(n);

you create v with n empty vectors and then you push back additional data after it. Then you try to sort it and you get UB with your comparator when it hits empty vectors you created.

Upvotes: 1

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726479

The problem is in this declaration of your vector:

vector<vector<int>> v(n);

It does not simply reserve n spots, it creates a vector with n empty vectors inside. Hence the first call to sortcol for any of these empty entries produces undefined behavior, because

return v1[0] < v2[0];

references non-existent element at position zero.

Replace the declaration with

vector<vector<int>> v;

to fix this problem. If you would like to reserve space for n entries, add a call to vector::reserve after the declaration:

vector<vector<int>> v;
v.reserve(n);

You should also pass vectors to your comparator by const reference, rather than by const value.

Upvotes: 4

Related Questions