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

有帮助吗?

解决方案

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.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top