4

I do not understand how the below piece of code yields the given output.

#include <iostream>
using namespace std;

class MyClass
{
   public: 
   void doSomething()
   { 
       cout<<"Inside doSomething"<<endl;  
   }
};

int main()
{   
    MyClass obj;
    MyClass *ptr=&obj;
    ptr->doSomething();
    ptr=NULL;
    ptr->doSomething();
}

Output


Inside doSomething
Inside doSomething

I executed a function with a null pointer and it actually calls the function. Retrieving the address stored in the ptr using cout of ptr shows that ptr is set to 0 after the statement ptr=NULL; .But it still calls doSomething().What is actually happening inside ?

2 Answers2

9

This is Undefined Behaviour, and absolutely anything could happen, including appearing to work. This is not reliable!!

In this case, it doesn't crash, simply because the MyClass::doSomething() function doesn't do anything with its this pointer (which would be NULL, so likely to cause a crash).

If you gave MyClass a member, and attempted to access that in doSomething(), I'd expect to see a crash (segfault):

class MyClass
{
   int someNum;
   public: 
   void doSomething()
   { 
       cout<< "Inside doSomething: " << this->someNum <<endl;  
   }
};

(And in my test with gcc 4.9.2. on Linux, I do indeed see a segfault.)


Also, please reconsider your use of bad practices using namespace std; and endl.

Community
  • 1
  • 1
BoBTFish
  • 19,167
  • 3
  • 49
  • 76
2

The reason is that you only access the code segment of the class which is always there.

But the moment you try to access any member variable from within the function you most likely will crash.

So, there is a hidden this pointer passed for every function, So after deleting the object this pointer is invalid.. So any access to this pointer will crash after the object was deleted.

Here is simplified version of what is happening internally:

doSomething(MyClass * this)
{
  // Will work OK if 'this' pointer is NULL, but NOT used.

  // Will Crash if 'this' pointer is used.
  this->data = 100;
}
vcp
  • 962
  • 7
  • 15
Sam Daniel
  • 1,800
  • 12
  • 22