In the following code, why does s1.printVal causes a dangling pointer error? Isn’t the s1 object, i.e. its pointer, still accessible until it’s destroyed?
class Sample
{
public:
int *ptr;
Sample(int i)
{
ptr = new int(i);
}
~Sample()
{
delete ptr;
}
void PrintVal()
{
cout << "The value is " << *ptr;
}
};
void SomeFunc(Sample x)
{
cout << "Say i am in someFunc " << endl;
}
int main()
{
Sample s1 = 10;
SomeFunc(s1);
s1.PrintVal(); // dangling pointer
}
The problem here is the copy that is done for argument of the
SomeFunc(). That copy de-allocates your pointer when destroyed. You need to also implement a copy constructor, and copy assignment operator. See rule of three.Edit:
Here’s “expanded” pseudo-code, i.e. what the compiler does for you in the
main()function:This is not the exact representation, but a conceptual explanation. It just helps to think in terms of what compiler has to do with your code.
The pointer member of
Sampleisdelete-ed at the step marked withXXX, and thendelete-ed again at the stepYYY.