mercredi 12 juillet 2017

C++ Segfault on simple sorting example

Take a look at this fairly straightforward sorting code:

#include <string>
#include <vector>
#include <iostream>
#include <algorithm>

using namespace std;

struct Student
{
    string Firstname;
    string Sirname;

    Student(const string& firstname, const string& sirname)
        : Firstname(firstname), Sirname(sirname)
    {
    }
};

bool Comparer(const Student& s1, const Student& s2)
{
    return s1.Firstname.compare(s2.Firstname);
}        

int main()
{
    vector<Student> students;

    for (int i = 0; i < 1000; i++)
        students.push_back(Student(string("John") + to_string(i), "Smith"));

    sort(students.begin(), students.end() - 1, Comparer);

    for (auto& student: students)
        cout << student.Firstname << endl;
}

On g++, std=c++11

g++ why.cpp -o why -std=c++11 -g

It causes a segfault. On GDB, a backtrace will show the code trying to copy memory from one location to another.

#0  __memcmp_sse4_1 () at ../sysdeps/x86_64/multiarch/memcmp-sse4.S:1011
#1  0x00007ffff7b76278 in std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >::compare(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const&) const () from /usr/lib/x86_64-linux-gnu/libstdc++.so.6
#2  0x0000000000401929 in Comparer (s1=..., s2=...) at why.cpp:21

I suspected that one of the strings was invalid so I added a conditional breakpoint like so:

break why.cpp:21 if s1.Firstname.empty()

And sure enough it hits it. The really weird thing is that if I change the iterator position like so:

sort(students.begin(), students.begin(), Comparer);

It works. I mean, what the heck? :)

Aucun commentaire:

Enregistrer un commentaire