dimanche 25 septembre 2016

Segmentation fault when pointer used as key points to something in std::unordered_map

I was testing std::unordered_maps to get used to them before actually using them in a project.

And I noticed that, if I use pointers as keys, I get a segfault error when the pointer used as the key actually points to a value. This is my code:

#include <unordered_map>
#include <stdio.h>

int main() {
    std::unordered_map<int*, int> map;

    int* key;
    //*key = 18;

    map[key] = 1893;

    printf("%d\n", map[key]);
}

Now, if I uncomment that commented line, I get a segmentation fault error, while if I leave it commmented, everything works perfectly. Why does this happen?

Aucun commentaire:

Enregistrer un commentaire