Aussie AI

Appendix: C++ Bug Catalog

  • Bonus Material for "Generative AI in C++"
  • by David Spuler, Ph.D.

“Round up the usual suspects.”

Casablanca, 1942.

 

 

Here's a long catalog of common C++ bugs. Some of these will be found by the compiler, some will get a warning, and some are insidious with no hints from the compiler at all.

Every programmer quickly becomes familiar with the phenomenon of run-time errors. These are errors that cause the program to crash, hang or produce incorrect output. In C++ there are some very common mistakes that cause run-time errors and this section is intended to document the most common errors. Making the programmer aware of the errors will hopefully diminish their occurrence.

Code blindness

There are many programming idioms that are commonly used by programmers and yet carry the risk of occasional serious errors. One of the main ways these errors get introduced is "copy-paste" of a block of code.

For example, one of the most common idioms is the use of an integer loop variable in a for loop. A correct for loop header looks like:

    for (i = 1; i <= 10; i++)

However, when programmers "copy-and-paste" program statements there are some errors that often arise. When asked to loop down from 10 to 1, a lazy programmer will copy and change the above for loop header — a highly error-prone practice. One such error is that ++ is not changed to -- as below:

    for (i = 10; i >= 1; i++) /* ERROR */

This will cause a loop that is (almost) infinite. It will terminate only when integer overflow causes i to become negative.

A similar use of copy-and-paste without due care has caused a similar error in the code below with nested loops:

    for (i = 1; i < n; i++)
        for (j = 0; j < n; i++) /* ERROR */
            arr[i][j] = 0;

Can you see the bug? It's hidden by "code blindness" if you can't.

More C++ Bug Catalogs