user6245072 user6245072 - 1 month ago 5
C++ Question

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

I was testing

s 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?


You declared a pointer, not an int. The pointer points to nowhere, as you did not initialize it. There is no place to write the 18 to, because the pointer doesn't point to any space.

Note that your issue is completely unrelated to unordered maps.
int * key; *key = 18; will dump in any context.

Use either
int key; key = 18;,
or if you really want key to be a pointer:
int * key = new int; key = 18;