tags:

views:

74

answers:

2
+2  Q: 

Dangling pointer

Does this piece of code lead to dangling pointer. My guess is no.

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();
}
+6  A: 

Yes. Sample's copy constructor gets called when you pass s1 to SomeFunc. The default copy constructor does a shallow copy, so ptr will get deleted twice.

A: 

Yes, as user said.

~Sample() {
  delete ptr; // Pointer deleted but left dangling
  ptr = NULL; // Pointer is no longer dangling
}

Note however, that any pointers you copied that pointer to will be left dangling unless they are set to NULL as well.

Big Al