0

I am preparing for a C++ test and came across this code example.

In the code example below, obj is passed to SomeFunc. SomeFunc has parameter Foo obj so a copy is made which results in a Foo being created and later destroyed when SomeFunc function returns.

If you change the function signature to:

SomeFunc(Foo& obj);

or better:

SomeFunc(const Foo& obj);

problem goes away.

What is puzzling however is why the code crashes on the obj.PrintVal(); line.

I can understand how on calling SomeFunc that a new Foo is created and destroyed when the function returns, but I thought that would be isolated to the local copy of obj in SomeFunc. But when I step through in my debugger I find that the ptr of obj in main is deallocated. and so on calling obj.PrintVal() - the dereference of ptr causes segmentation fault / access violation.

Can someone please explain what is happening.

#include <iostream>

class Foo 
{
public:
    int *ptr;
    Foo(int i) {
        ptr = new int(i);
    }

    ~Foo() {
        delete ptr;
    }

    int PrintVal() {
        std::cout << *ptr;
        return *ptr;
    }
};

void SomeFunc(Foo obj) {
    int x = obj.PrintVal();
}

int main() {
    {
    Foo obj= 15;
    SomeFunc(obj);

    obj.PrintVal();
    }

    return 0;
}
Mats Petersson
  • 126,704
  • 14
  • 140
  • 227
Angus Comber
  • 9,316
  • 14
  • 59
  • 107

1 Answers1

2

It's "crashing" because you have made a copy of that pointer unintentionally, and the delete is called on an already deleted pointer.

You need to provide a copy constructor (different from the automatically created one), that does handle this correctly (create a new pointer for the copy).

πάντα ῥεῖ
  • 1
  • 13
  • 116
  • 190