문제

#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