sort function C++ segmentation fault

前端 未结 3 1689
面向向阳花
面向向阳花 2021-02-04 08:06

In this code, for vector size, n >=32767, it gives segmentation fault, but upto 32766, it runs fine. What could be the error? This is full code.

#include

        
3条回答
  •  天涯浪人
    2021-02-04 08:52

    C++ acts weird sometimes. I got Segmentation fault in basic_string.h file! I was upgrading my code base to GCC 5.4.0 from GCC 4.2.1 and suddenly this SEG FAULT occurred and I was wondering why the same code was working earlier and now it is breaking inside C++ own STL. Then I looked up the back trace and found that it was coming from std::sort for vector of pointers, which was using custom comparator to compare the pointers on the basis of fetching the object's name by member function ptr->GetName(). This GetName() was returning a string.

    I spent a whole day on figuring out what maybe the change in basic_string file to cause this fault. Then I got to know about this "Strict Weak Ordering" thing and I changed my comparator function accordingly. Still no luck.

    Then I tweaked around and changed the original comparator function to a Functor. And now, it worked. I don't know exactly the reason behind it but it worked.

    Here is my original comparator function :

    bool swap (CLwPatternObj *a, CLwPatternObj *b){
        return a->GetName() < b->GetName() ) 
    }
    

    And here is the new Function Object.

    class CLwPatternComparator
    {
    public:
        bool operator() (CLwPatternObj *a, CLwPatternObj *b) 
        {
            return a->GetName() < b->GetName();
        }
    };
    

    Same logic, but it works with Function Object.

提交回复
热议问题