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

Actions

Information

2 responses

30 07 2008
HemantD

Wow Amazing ….!!!

30 07 2008
Jijo.Raj

😉

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s




%d bloggers like this: