Sunday, May 30, 2010

Uninitialized pointer and member functions

A very unpleasant scenario possible when you forget to initialize a pointer to a class. Let's say, we have class CBase with a member function which doesn't use member data, i.e. it doesn't need this pointer.

This is an undefined behavior by the Standard. But sometimes it works. Visual Studio 2008, for example, generates a working code. The function call is resolved during the compilation, we don't use this. And you remain oblivious for a long period of time. Here is a scarier looking example

((CBase*)0)->f();

But when you try to use this pointer, you program "crashes". Examples: