mardi 8 janvier 2019

seg fault/undefined behavior in comparator function of std::map

this has been confusing me today.

I'm having trouble understanding why the code below seg faults on the final insertion into the test_map. Using emplace(), insert() both work as expected, but using the [] operator fails. I've read the relevant C++ documentation for [] but the behavior observed below doesn't seem to match up with what i've read.

I've stepped through in GDB and noted that it was failing when trying to compare strings inside the comparator function.

#include <iostream>
#include <map>
#include <iostream>

class Testkey {
public:
    std::string s1;
    int64_t id;
    Testkey(const char* s1_, int64_t id_): s1(s1_), id(id_) {}

    bool operator<(const Testkey& rhs) const {
        if (s1 < rhs.s1)
            return true;
        if (id < rhs.id)
            return true;
        return false;
    }
};

int main() {
    Testkey i1("69739", 748072524);
    Testkey i2("69728", 52608624);
    Testkey i3("69725", 750212380);
    Testkey i4("68988", 55027788);

    std::map<Testkey, int> test_map;
    test_map[i1] = 1;
    test_map[i2] = 2;
    test_map[i3] = 3;
    std::cout << "hmm.." << std::endl;
    test_map[i4] = 4; // seg faults here in comparator function...
    std::cout << "done" << std::endl;
    return 0;
}

I've attached a repl here https://repl.it/repls/RundownSparklingComment

Aucun commentaire:

Enregistrer un commentaire