The Basics of C Programming

Pointers: Common Bugs

Bug #1 - Uninitialized pointers

One of the easiest ways to create a pointer bug is to try to reference the value of a pointer even though the pointer is uninitialized and does not yet point to a valid address. For example:


	int *p;

	*p = 12;

The pointer p is uninitialized and points to a random location in memory when you declare it. It could be pointing into the system stack, or the global variables, or into the program's code space, or into the operating system. When you say *p=12;, the program will simply try to write a 12 to whatever random location p points to. The program may explode immediately, or may wait half an hour and then explode, or it may subtly corrupt data in another part of your program and you may never realize it. This can make this error very hard to track down. Make sure you initialize all pointers to a valid address before dereferencing them.

Bug #2 - Invalid Pointer References

An invalid pointer reference occurs when a pointer's value is referenced even though the pointer doesn't point to a valid block.

One way to create this error is to say p=q;, when q is uninitialized. The pointer p will then become uninitialized as well, and any reference to *p is an invalid pointer reference.

The only way to avoid this bug is to draw pictures of each step of the program and make sure that all pointers point somewhere. Invalid pointer references cause a program to crash inexplicably for the same reasons given in Bug #1.

Bug #3 - Zero Pointer Reference

A zero pointer reference occurs whenever a pointer pointing to zero is used in a statement that attempts to reference a block. For example, if p is a pointer to an integer, the following code is invalid:

p = 0;
*p = 12;

There is no block pointed to by p. Therefore, trying to read or write anything from or to that block is an invalid zero pointer reference. There are good, valid reasons to point a pointer to zero, as we will see in later articles. Dereferencing such a pointer, however, is invalid.

All of these bugs are fatal to a program that contains them. You must watch your code so that these bugs do not occur. The best way to do that is to draw pictures of the code's execution step by step.