Possible Duplicate:
Why am I able to make a function call using an invalid class pointer
class B
{
public:
int i;
B():i(0){}
void func1()
{
cout<<“func1::B\n”;
}
void func2()
{
cout<<“i = “<<i;
}
};
int main()
{
B *bp = new B;
bp->func1();
delete bp;
bp = NULL;
bp->func1();
bp->func2();
return 1;
}
Output:
func1::B
func1::B
Runtime Exception:
NULL pointer access
This is the same old story of
NULL(or invalid) object pointers; for the standard, calling a method on aNULLobject pointer results in undefined behavior, which means that, as far as the standard is concerned, it could work perfectly fine, it could blow up the computer or kill some random people.What happens here is a consequence of the typical implementation of classes by C++ compilers: classes usually are actually structures that contain just the fields, and all the methods are actually functions which take as a hidden parameter the
thispointer.Now, in this kind of implementation if you call a method with a
NULLthispointer, if it doesn’t access any of the fields it won’t actually dereferencethis, so it should run fine (as happens withfunc1).If, instead, the method tries to access any of the fields (e.g.
func2), it will dereference thethispointer, which, beingNULL, will lead to a crash (dereferencing aNULLpointer it’s, again, undefined behavior, but usually it results in a crash).Note that if the methods that you’re calling are virtual it’s almost sure that calling them with a
NULLthispointer will lead to a crash, since the virtual calls are resolved via the vtable (a function pointer array), which is hidden at the beginning of the class.By the way,
void main()is not standard; it should beint main()(argvandargcare, instead, optional).