Interview Questions

What is a dangling pointer?

C++ Interview Questions and Answers


(Continued from previous question...)

11. What is a dangling pointer?

   
A dangling pointer arises when you use 
the address of an object after
its lifetime is over. This may occur 
in situations like returning
addresses of the automatic variables
from a function or using the
address of the memory block after 
it is freed. The following
code 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 is
called it is called by the pointer that has been
freed by the       destructor in SomeFunc.

(Continued on next question...)

Other Interview Questions