Function call by using null pointer will crash?

26 06 2008


Crash on function call by using null pointer – The ultimate C++ Nirvana. 😉 Whether function call by null pointer always crash? Is it possible to call functions by using null pointer without crash? Check the following code snippet. Whether it will crash?

// Console Helper class.
class ConsoleHelper
{
public:
    // Prints a line to console.
    void PrintLine()
    {
        cout << "---------------" << endl;
    }
};

// The one and only one Main.
int main(int argc, char* argv[])
{
    // Call the function by using null pointer.
    ConsoleHelper* pConsoleHelper = 0;
    pConsoleHelper->PrintLine();

    return 0;
}


It won’t crash. Because in the function call we’re not accessing any member variables. Function call by using null pointers crash only if we’re accessing some member variables. Its because for every object function call, the object address is pushed to the function stack as “this” pointer. If the object pointer is null, then the “this” pointer also become null and hence the crash!


Null pointers are not that much bad! isn’t it? 😉


Targeted Audience – Intermediate.

Advertisements