c++ - 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 doing wrong?
you segmentation fault because pointer has not been assigned:
c* c = new c; // <<== add c->us.insert(2); delete c; // <<== free memory unlike objects declared objects, not pointers (e.g. c c;) pointers need initialized: should either assign them address of existing object, or allocate memory new object using operator new. dereferencing uninitialized pointers considered undefined behavior, causing segmentation faults.
Comments
Post a Comment