开发者

Dangling pointer

开发者 https://www.devze.com 2023-01-02 05:18 出处:网络
Does this piece of code lead to dangling pointer. My guess is no. class Sample { public: int *ptr; Sam开发者_如何学Cple(int i)

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

class Sample
{
public:
int *ptr;
Sam开发者_如何学Cple(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();
}


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.


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.


When you pass the object to SomeFunc() by value, shallow copy is taking place and after its execution, the memory ptr was pointing to has been deleted... so when you call the PrintVal () function on s1 and try to dereference the pointer, your program may crash at this stage.... you can delete a pointer once and its memory becomes out of your control

0

精彩评论

暂无评论...
验证码 换一张
取 消