1

Possible Duplicate:
Accessing class members on a NULL pointer

I know dereferencing a NULL pointer crashes the program or give undefined behavior. But following program consistently prints This is a car how many ever times I run. Checked in Linux (g++) and AIX (xlc++).

#include <iostream>
using namespace std;

class Car
{
public:
    void display(){ cout << "This is a car" << endl; }
};

int main()
{
    Car *c = NULL;
    c->display();
}

When I add one data member for the class and try to print the value of that, then the program crashes.

class Car
{
     int i;
 public:
     void display(){ cout << "This is a car" << i << endl; }
};

So it seems it is fine to dereference a NULL pointer and call a member function which does not access a data member of the class. Is that really an undefined behavior?

Community
  • 1
  • 1
Sanish
  • 1,699
  • 1
  • 12
  • 21
  • Yes, it is really undefined behaviour. Undefined behaviour is not "guaranteed to not do what the user expects". So, no, it's not fine to dereference a null pointer. Why? *Because there's no sane reason you would want to*. – R. Martinho Fernandes Jul 09 '12 at 14:21

0 Answers0