By Stephen R. Davis

Part of Beginning Programming with C++ For Dummies Cheat Sheet

In C++, a pointer is a variable that contains the address of an object in the computer’s internal memory. Use these steps to avoid problems with pointers in C++:

  1. Initialize pointers when declared.

    Never leave pointer variables uninitialized – things wouldn’t be too bad if uninitialized pointers always contained random values – the vast majority of random values are illegal pointer values and will cause the program to crash as soon as they are used. The problem is that uninitialized variables tend to take on the value of other, previously used pointer variables. These problems are very difficult to debug.

    If you don’t know what else to initialize a pointer to, initialize it to nullptr. nullptr is guaranteed to be an illegal address.

  2. Zero out pointers after you use them.

    Similarly, always zero a pointer variable once the pointer is no longer valid by assigning it the value nullptr. This is particularly the case when you return a block of memory to the heap using delete; always zero the pointer after returning heap memory.

  3. Allocate memory from the heap and return it to the heap at the same “level” to avoid memory leaks.

    Always try to return a memory block to the heap at the same level of abstraction as you allocated it. This generally means trying to delete the memory at the same level of function calls.

  4. Catch an exception to delete memory when necessary.

    Don’t forget that an exception can occur at almost any time. If you intend to catch the exception and continue operating (as opposed to letting the program crash), make sure that you catch the exception and return any memory blocks to the heap before the pointers that point to them go out of scope and the memory is lost.

  5. Make sure that the types match exactly.

    Always make sure that the types of pointers match the required type. Don’t recast a pointer without some specific reason. Consider the following:

void fn(int* p);
void myFunc()
    char c = 'a';
    char* pC = &c;

The above function compiles without complaint since the character pointer pC has been recast to an int* to match the declaration of fn(int*); however, this program will almost surely not work. The function fn() is expecting a pointer to a full 32-bit integer and not some rinky-dink 8 bit char. These types of problems are very difficult to sort out.