Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c++ std::set insert causing segmentation fault

Tags:

c++

set

stl

All-

I can't quite figure out why this piece of code is resulting in a segmentation fault... Any help would be great.

#include <iostream>
#include <set>

using namespace std;

class A{
public:
    int _x;

    A(int x){
        _x = x;
    }
};

bool fncomp(A a1, A a2){
    return a1._x < a2._x;
}

int main(){
    bool(*fn_pt)(A,A) = fncomp;

    set<A, bool(*)(A,A)> testSet;
    for(int i=0; i<10; i++){
        cout << i << endl;
        A a(i);
        testSet.insert(a);
    }
}

The output is:

0
1
Segmentation Fault
like image 950
poy Avatar asked Oct 22 '25 02:10

poy


1 Answers

Well, look at your code. You declared a function fncomp, but are you really using that function anywhere? You initialize fn_pt with it, but fn_pt is not used anywhere. Doesn't it seem strange to you? How do you expect your testSet object to know that you want it to use your fncomp as the comparator, if you never ask your set object to use that function?

You declared your set testSet with an ordinary function pointer type bool(*)(A,A) as a comparator type. That's the type of the comparator. Now, you have to pass the actual value of the comparator to your set object through the constructor parameter

set<A, bool(*)(A,A)> testSet(fn_pt);

or

set<A, bool(*)(A,A)> testSet(fncomp);

(You don't really need that intermediate pointer fn_pt).

You forgot to do that, and the set object used the default constructor argument value for the comparator, which in this case is a null pointer. So, every time your testSet object tries to compare two elements, it performs a function call through a null pointer. No wonder it crashes.

like image 76
AnT Avatar answered Oct 23 '25 17:10

AnT



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!