Common Errors

Learn how to avoid common mistakes in pointer code.

Now that we know the basics of using pointers, let’s look at some of the common errors encountered in pointer-intensive code.

Uninitialized pointers

We covered this one a bit in the previous lesson, but we’ll go over it one more time since it’s important.

When we create a pointer doing something like double* ptr, ptr is placed in a memory location chosen by the operating system. Without initialization, ptr will contain garbage, whatever remained in the memory from previous usage or random data. If we try to work with such a pointer and dereference it to read or write to it, the code will try to read or write to an address specified by that garbage value. It causes undefined behavior, and we have no idea what will happen:

  • The garbage data doesn’t represent a valid address, and the operating system will terminate the program with a lovely “segmentation fault” message.
  • By pure luck, that garbage data represents a valid address, but our program
...