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.
class CBase
{
int i;
public:
void f() { std::cout<<"CBase::f"<<std::endl;}
};


And after that you write the following code somewhere:

CBase* p = NULL;
p->f();


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:
class CBase
{
int i;
public:
virtual void f() { std::cout<<"CBase::f"<<std::endl;}
};

class CBase
{
int i;
public:
void f() { std::cout<<"CBase::f"<<std::endl; i=0;}
};


All this leads to very interesting, hard to find bugs.

Links:
comp.lang.c++.moderated - Functions that don't use this, called with uninitialized pointers

3 comments:

cottonvibes said...

hmm never had that specific problem before, but I can see how it will be an odd bug to figure-out if it were to happen in practice.
Thanks for the tip.

Alena said...

cottonvibes
Thanks for the tip

You're welcome! :-)

xanep said...

If function does not use this pointer shouldn't it be static? I really don't see any problem in calling such function with zero pointer. Can you describe "hard-to-find" bug scenario?