Why doesn't this C++ code result in a segmentation fault?

I wrote the following code to test my understanding of heap vs stack allocations in C++:

    #include <iostream>
    
    class A {
      int x_;
     public:
      explicit A(int x) {
        x_ = x;
      }
      void print() {
        std::cout << x_ << "\n";
      }
    };
    
    class B {
     public:
      A* a_;
    };
    
    void foo(B* b) {
      A a(3);
      b->a_ = &a;
    }
    
    int main()
    {
      B* b = new B();
      foo(b);
      b->a_->print();
      delete b;
    }

My expectation was that b->a_->print(); would result in a segmentation fault, because a_ is a pointer to an object that was provisioned in foo's stack and destructed when foo exits. But it actually prints 3. Why doesn't this segfault?



from Recent Questions - Stack Overflow https://ift.tt/2RXwEUA
https://ift.tt/eA8V8J

Comments

Popular posts from this blog

Spring Elasticsearch Operations

Network Error and Timeout on Authorize.net JS

Object oriented programming concepts (OOPs)