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;


void foo()


cout << "Hello" << endl;

//i = 5;




int main(int argc, char* argv[])


MyClass *mc;


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 (4)

  1. Shahar Prish says:

    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.

  2. Shahar Prish says:

    (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)

  3. Compilers already do these runtime checks. See the VS 2005 compiler options /RTC* specifically /RTCu. But these are checks over and above C++ spec and many compilers either do not do it. Many developers are not aware of the switches either and they go unnoticed

    In most shops people turn these checks-on in debug builds, but turn-it off in release builds. Long time back when I was working on C++, as a fix I added some code to a utility method and saw the app crash with invalid memory access. Code as above turned out to be the cause.

  4. Sometime back I had posted about a case where non-virtual calls are used for virtual methods and promised

Skip to main content