title: Dangling pointer example
body: <p>In the following code, why does <code>s1.printVal</code> causes a dangling pointer error? Isn't the <code>s1</code> object, i.e. its pointer, still accessible until it's destroyed?</p>
  
  <pre><code>class Sample
  {
    public:
      int *ptr;
      Sample(int i)
      {
          ptr = new int(i);
      }
  
      ~Sample()
      {
          delete ptr;
      }
      void PrintVal()
      {
          cout &lt;&lt; "The value is " &lt;&lt; *ptr;
      }
  };
  
  void SomeFunc(Sample x)
  {
      cout &lt;&lt; "Say i am in someFunc " &lt;&lt; endl;
  }
  
  int main()
  {
      Sample s1 = 10;
      SomeFunc(s1);
      s1.PrintVal(); // dangling pointer
  }
  </code></pre>
  
  <p><a href="http://www.techinterviews.com/c-object-oriented-questions" rel="nofollow noreferrer">Source</a></p>