1

I think I understand the basic ideas behind pass-by-value and pass-by-reference. I have created a toy code to explain my question:

class C2 {
  public:
    int val;
    C2() {}
    ~C2() {}
};

class C1 {
  public:
    C2 * x;
    C1(C2 & x_) {
      x = &x_;
    }
    C1() {}
    ~C1() {}
};

void func (C1 & y) {
  C2 z;
  z.val = 5;
  y = C1(z);
}

void func_p (C1 & y) {
  C2 * z;
  z = new C2();
  z->val = 5;
  y = C1(*z);
  delete z;
}

int main()
{
  C1 m_y1;  
  func(m_y1);
  cout << m_y1.x->val << endl; // Prints 5

  C1 m_y2;
  func_p(m_y2);
  cout << m_y1.x->val << endl; // Prints junk instead of seg fault 

  return 0;
}

I had the following questions:

  1. How can the first cout print 5. Object z is local to func, and would go out of scope after func is exited. So accessing a pointer pointing to z (in this case x in C1) should have resulted in a segmentation fault?
  2. The second cout prints junk (32766 or so). Since z is deleted in func_p shouldn't this also result in segmentation fault?

Edit: Thank you (I will delete this question since it was flagged for duplicate and I can understand why it is duplicate. I just got entagnled with these reference passes!) Just to clarify my understanding, please consider func_c

void func_c (C2 & y) {
  C2 z;
  z.val = 5;
  y = z;
}

int main()
{
  C1 a;

  a.x = new C2();
  func_c(*(a.x));

  cout << a.x->val << endl; // Prints 5
}

I am assuming this will be a defined behavior because the copy function will be called. Initially a.x = new C2(), and after func is called, z object is copied into a.x?

  • `m_y1.x->val` exhibits undefined behavior, by way of accessing an object after its lifetime has ended. "Seems to work" is one possible manifestation of undefined behavior. "Prints junk" is another. – Igor Tandetnik Aug 03 '20 at 03:10
  • You do not need to delete your question. It's fine to leave it undeleted but closed as a "signpost" to the other answer. – Daniel Widdis Aug 03 '20 at 06:52

1 Answers1

1
  1. How can the first cout print 5.

Because the behaviour of the program is undefined.

  1. ... Since z is deleted in func_p shouldn't this also result in segmentation fault?

There is no requirement for there to be a segmentation fault. The behaviour of the program is undefined.

eerorika
  • 232,697
  • 12
  • 197
  • 326
  • Thank you. I will delete this question as it seems to be a duplicate. But, before that I had one question to solidify my understanding, have edited the question. – Andrew Mathews Aug 03 '20 at 03:51
  • @AndrewMathews Yes. The new example is well defined as far as I can tell. – eerorika Aug 03 '20 at 03:52
  • Thank you! I had this issue with a larger code base, and was going mad debugging it. I will delete this question in a short while. – Andrew Mathews Aug 03 '20 at 03:53