Search code examples
c++c++11segmentation-faultunordered-set

Segmentation Fault with a pointer to an object holding an unordered_set


#include <unordered_set>

class C {
public:
    std::unordered_set<int> us;
};

int main() {
    C* c;
    c->us.insert(2); // Segmentation Fault
}

What am I doing wrong?


Solution

  • You get a segmentation fault because the pointer has not been assigned:

    C* c = new C; // <<== Add this
    c->us.insert(2);
    delete c;    // <<== Free the memory
    

    Unlike objects declared as objects, not as pointers (e.g. C c;) pointers need to be initialized: you should either assign them an address of an existing object, or allocate memory for a new object using the operator new. Dereferencing uninitialized pointers is considered undefined behavior, often causing segmentation faults.