SatView: Pointer Perfect, part 4
(Page 1 of 5 )
In our final article in the series covering pointers, J. Nakamura discusses the various pitfalls of wild pointers and how to avoid them.
In the previous articles I have shown you how to use pointers, pointer pointers and smart pointers. To round it off I thought it would be nice to take a look at some of the common pitfalls you might wander into using pointers. It is quite easy to say that using pointers can be quite troublesome, but I learn best from examples; so let me demonstrate what not to do with pointers.
Wild Pointers
A wild pointer is a pointer that refers to garbage. We have seen how we can retrieve pointers to objects and how we can create them. The most common error you could make when using a pointer is using one that is uninitialized.
Uninitialized Pointers
Sometimes it is not necessary to immediately instantiate a pointer.
class Base {
public:
virtual ~Base();
/* more stuff here */
};
class DerivedA : public Base {
public:
virtual ~DerivedA();
/* more stuff here */
};
class DerivedB : public Base {
public:
virtual ~DerivedB();
/* more stuff here */
};
Base* foo(EFlag flag) {
Base *result;
switch (flag) {
case FLAGA:
result = reinterpret_cast<Base*>(new DerivedA);
break;
case FLAGB:
result = reinterpret_cast<Base*>(new DerivedB);
break;
}
return result;
}
The code above demonstrates bad usage of the switch statement. I would like to mention that you should always implement the default case (even when you are sure that only FLAGA and FLAGB exist!) and fire an assert (or return/deal with an error code) when that code is hit. My purpose however is to demonstrate what an uninitialized pointer looks like, and it is clear that when flag != FLAGA or flag != FLAGB, the pointer it returns is uninitialized.
At the time of implementation, the programmer who wrote this might have been certain that only FLAGA and FLAGB are used for EFlag… but this might (read: will) change in the future. When a FLAGC is introduced and this code is overlooked, the contents of the result are uninitialized. This means that it points to garbage. This can become really troublesome to detect, as your application might still function correctly for a while…or every other time! It is better to immediately crash than have trash around. Always initialize pointers you are not using yet to NULL; this will give you the opportunity to check the validity of a pointer before you try to use it:
void test() {
Base *pBase = foo();
assert(pBase);
PBase->MoreStuffHere();
}
Next: Fence Post Errors >>
More C# Articles
More By J. Nakamura