Jaa


Null pointer access in C++

Language implementation quirks can lead to interesting things. Lets say I have the following C++ code.

 class MyClass{    int i;public:    void foo()    {        cout << "Hello" << endl;        //i = 5;    }}; int main(int argc, char* argv[]){    MyClass *mc; mc->foo();     return 0;}

What is the outcome of this piece of code? Since we haven't allocated mc and accessing foo via an unassigned pointer most people expect a crash. However on most compilers this is garaunteed to print "Hello" with out any crash.

What is important to note here is that since foo is not a virtual method the lookup doesn't go through the vtable and hence mc->foo() call is compiled here as MyClass::foo(null)through appropriate mangled name). As long as foo doesn't access any of the instance member of MyClass the null this pointer remains unused. If the commented line is foo is uncommented we get a crash.

If the foo method is made virtual then lookup goes thrugh the vtable and the application crashes.

Comments

  • Anonymous
    August 03, 2006
    That is not entirely true.

    To be more accurate, you should say: "This is garaunteed to work in all Microsoft VC++ compilers up to the one shipping with Visual Studio 2005".

    There is nothing in the C++ standard that prohibits compilers to add runtime checks or actually making use of the "this" ptr when executing non-virtual methods.

    Furthermore, there are places where an implicit usage of "this" happen even when you do not call virtual methods. RTTI comes to mind. Doing dynamic_cast<>() on an uninitialized ptr will give you some bad runtime errors.
  • Anonymous
    August 03, 2006
    (Oh yeah, and when I said "up to the one shipping with VS2005, I meant to say "Up to and including the one shipping with VS2005)
  • Anonymous
    August 03, 2006
    The comment has been removed
  • Anonymous
    July 02, 2008
    Sometime back I had posted about a case where non-virtual calls are used for virtual methods and promised