What Is A Dangling Pointer In C++


  • 8 Dec, 2011

    A dangling pointer arises when you use the address of an object afterits lifetime is over. This may occur in situations like returningaddresses of the automatic variablesfrom a function or using theaddress of the memory block after it is freed. The followingcode snippet shows this: 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(); }In the above example when PrintVal() function iscalled it is called by the pointer that has beenfreed by the destructor in SomeFunc.

    Comments Received:
    Please give your suggestions and feedback:

2009-2016 downloadmela.com. All rights reserved.