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 doesn’t have access to it. It can happen if the address points to a memory area reserved by the operating system or not allocated for our program.
  • By pure luck, that garbage data represents a valid address, and our program has the right to use it. Then we’ll read or write in random memory locations, very likely corrupting data and breaking the entire program.

Segmentation fault means that the operating system determined that our program is trying to access an invalid memory address. The address could be not allocated, not exist, or we don’t have the right to use that memory area. Either way, the operating system will block the access and terminate the program.

In short, do not do this:

Get hands-on with 1200+ tech skills courses.