Why this program is not crashing up?

 

It was a question I faced in an interview.

The question was as follows

class Test
{
public:
          void Disp(int i)
          {
                    int x = i*100;; // Just for the sake of some complexity :)
                    printf(“%d,%d”,i,x);
          }
};

int main()
{
          Test* t = NULL;
          t->Disp( 123);
          return 0;
}

What is the output of this program? Will it crash?

In the first look we may seem that this program would crash. But it wont!

It will simply prints 123,12300.

The explanation would be very easy if you know the internal working of a function call of a class.

As you all know. Functions and classes are like templates. There will be only one definiton for functions in Memory even if we have different number of objects in the class.

t->Disp(123) will be replaced by compiler something like this.

Test::Disp(Test* this, int i);

The value of parameters will be t, 123 repectively. (just remember every non static memeber functions of a class will have a “this” pointer which refer to the object itself)

Inside the Disp function, we are using some independant data which is defined only in stack and not depends to the “t”. Thus inside the Disp function we are not using this pointer. So there is not a chance for access violation to make a memory crash.

But things will change if we change if we access the “this” pointer.

Suppose Test class is having member named m_IDNum of type int; (type of object not making a sense here. make it any type). If we access it like this,

void Disp(int i)

   m_IDNum= 10; // crashes the program :(

   …

}

This will make an access violation because it’s accessing “this pointer”.    m_IDNum= 10; will be translated as this->m_IDNum= 10; by compiler. As we wrote in the program the object is not allocated.

So in the sense Disp function is not making a sense and working as a simple global or static function(still not making a sense of static function :) ). I used this for the sake of an example. Hope nobody will write a code somethihg like this.

 
  • http://poonaji.blogspot.com anoop

    u r attending interviews from Japan ? i will forward ur blogpost to Unni!!

  • Nitheesh

    Nice One!

  • Karmegam

    Useful. Greetings !

    Thanks