Common Causes of Bugs
◀ Debugging Using Debugging Tools▶ Arrays Versus Pointers Amazon
In this chapter I would like to give you a list of common sources of bugs and suggested ways to prevent them so that you are equipped with this knowledge and will be able to avoid falling victim to those bugs. This knowledge alone can save you hours of debugging; so it is IMPERATIVE that you have it!
- Incorrect use of variables, including using C++ keywords as variable names and confusing classes’ names with their instances’, is a common source of bugs. Stick to a naming convention and do not use C++ keywords to name anything (refer to Appendix A for a list of C++’s keywords). If you use a C++ keyword to name a variable, the errors the compiler gives may not indicate the cause directly and it may take some time before you realize it.
- Preconditions of a function are not preserved right before calling it. For example, if a function does not handle certain arguments which are passed to it, errors result. So make sure the function can deal with them. I can’t emphasize enough how important it is. When you write a function, put its preconditions and postconditions inside comments and make sure it can deal with all types of arguments passed to it.
- Disorganized style of programming often results in incorrect nested loops or omission of necessary brackets. So make sure you adopt good coding style, especially indent lines appropriately.
- Unexpected program flow control is a common cause of logic bugs. For example if you use if-else statements, think about what they should be followed by. Given different conditions the program flow at runtime can be totally different. During the design phase, go through each possible program flow to see if each leads to desired result.
- Incomplete understanding of the programming language is a serious problem. If you use a statement or a standard function, make sure you know exactly what it does. For instance, cin >> skips spaces, tabs, and newlines but cin.get(char) doesn’t. Many C++ standard functions are very useful, but when you are about to use them, know exactly what they do, what their preconditions are, and how they deal with exceptions. You need to know your tools before you use them.
- In a big program, incomplete knowledge of the state of variables at any point in time could cause major problems. As an example, sometimes we use an array to store data, then at one point we want to do some operation on it in order to get information we need, then we forget to restore the array to its previous state. Sometimes we shouldn’t restore it but we accidentally do. In either case, bugs result. To keep disasters from happening, you need to be clear on the state of variables at any time when the program is running.
On average human hair grows about 6 inches a year.
◀ Debugging Using Debugging Tools▶ Arrays Versus Pointers