Search code examples
c++graphmultimap

map/set iterator not dereferencable. Multimap container isse


I'm geting this error message map/set iterator not dereferencable When trying to get value by key in multimap. In this code I'm trying to show nonoriented graph represented by adjacency list (vector<Vertex*> vertexList)

void NonOrGraph::show() {

    cout << endl;
    multimap<int, int> used;
    for (int i = 0; i < vertexList.size(); i++) {
        if (vertexList[i]->adjMap.empty()) {
            cout << vertexList[i]->index << " isolated";
        } else {
            for(map<Vertex*, int>::iterator it = vertexList[i]->adjMap.begin();
                                                 it != vertexList[i]->adjMap.end();
                                                 it++)
            {

                int from = vertexList[i]->index;
                int to   = it->first->index;
                int weight = it->second;

                used.insert(pair<int, int>(from, to)); 
                if (used.find(to)->second != from) {
                    cout << from << " <--(" << weight << ")--> " << to << endl;
                }
            }
        }
    }

    cout << "\n\n";

}

Solution

  • The problem is likely here:

    if (used.find(to)->second != from) {
    

    If to is not in used, used.find() will return used.end(), which you then dereference. It is undefined behavior to dereference the end() iterator, which in this case manifests by giving you a runtime error.

    You have to check the iterator against end() first:

    std::multimap<int, int>::iterator multi_it = used.find(to);
    if (multi_it != used.end() && multi_it->second != from) {
    //                        ^^^^^^^^^^^^^^^^^^^^
    //                        now, it's safe to dereference