Is it possible that I call function with NULL object without segfaulting?

Oh yes it is!

While debugging my project at work I came across this interesting piece. Inspector (watch or expressions in visual studio) showed me the variable with which the function was being called was NULL (0x0) i.e. considered invalid and still the function call went fine. This variable was initialized later. I thought this should be one of the weird things that compilers and IDEs do sometimes but no it was not like that and i observed the same behavior with restarting the IDE and changing the compiler.

If your class does not have data associated with it (member variables) then its functions can be called without allocating any memory to it.

e.g. following class and example:

class A
{
public:
void printA() { cout << “A\n”; }
void printB() { cout << “B\n”; }
};

int main ()
{
A * a = NULL;
a->printA();
a->printB();
}

Then for MS compiler cl.exe, you can call a function from a NULL object as far as you don’t access the variable even if you have defined it.

class A
{
int i;
public:
void printA() { cout << “A\n”; }
void printB() { cout << “B\n”; }
};

int main ()
{
A * a = NULL;
a->printA();
a->printB();
}

This will SEGFAULT.

class A
{
int i;
public:
void printA() { cout << “A\n” << i; }
void printB() { cout << “B\n”; }
};

int main ()
{
A * a = NULL;
a->printA();
a->printB();

and yes, you can do this in C++ and not Java.

Advertisements