dimanche 4 octobre 2020

pointers to vector of unordered_set become invalid, segfault [duplicate]

The aim is to create a map int |-> unordered_set, where the sets that are the values in the map, are allocated without using new.

The code below attempts to do this, but crashes with segfault.

#include <bits/stdc++.h>

using namespace std;

int main() {
    vector<unordered_set<int>> storage;
    map<int, unordered_set<int>*> m;
    // storage.resize(2);
    storage.emplace_back(unordered_set<int>{2});
    m[2] = &storage.back();
    storage.emplace_back(unordered_set<int>{8});

    unordered_set<int>* c0 = m[2];
    c0->insert(3); // Segmentation fault (core dumped)

    cout << "Does not reach here" << endl;
    return 0;
}

When searching this answer comes up, but this situation is different because the code here does not use the new keyword anywhere.

How can this be done without a crash, in a completely safe way? Any recommendation or best practice when it comes to pointers and containers?

Aucun commentaire:

Enregistrer un commentaire