Skip to main content

Introduction to Debugging

Debugging is the process of identifying and fixing bugs in a piece of code.

There are two general categories of errors in programs:

  1. Syntactic - errors that prevent you from creating an executable. Typically these types of errors that your compiler will provide to you
  2. Logical - errors where the program has some flaw that prevents the correct result from being generated.

Some errors are a bit blurry in that it can be classified as both syntactic and logical...

Between the two types of errors, syntactic errors are typically easier to find once you learn to read the error messages generated by your compiler.

Beyond these errors, as professional programmers, your programs should also follow consistent stylistic guidelines. In IPC144, please follow the Style Guide in these course notes.

In this section of the notes, we will go over some of the processes to identifying bugs within a piece of code.

Identifying bugs:

Prepare for debugging:

  1. Understand the problem you are trying to solve. Debugging is different from a walkthrough because you must also understand what problem the code is trying to solve. While you can fix most syntactic errors without this step, you won't be able to fix any of the logical errors unless you know what the code is suppose to do
  2. Properly format the code... if the code is sloppy, you will find it much harder to understand and fix the code. This means you should start by minimally correctly indenting all the code. This will also help you see the logical structure of the code.
tip

if you are asked to find fix stylistic bugs, you may wish to fix all the stylistic errors first before you do the next step as the process of styling your code can often inform structural issues with the code

Debugging syntax errors

Here are some common ones but there are others out there: - all brackets (round, curly and square) are correctly matched. - all variable names are consistently spelled - are there missing semicolons - using = where == should have been used or vice versa - are there typos? (Mismatched variable names, library name errors etc.)

Debugging logical errors

  • are there any errors involving program flow?
  • are variables initialized where needed?
  • are there any errors in mathematical expressions?
  • walkthrough the code:
    • create a set of inputs where you know what the result should be according to the specifications
    • walkthrough the program using your inputs and see if you get the expected results.
    • do all test cases fail to create the expected results or is it only some of test cases. If it is some test cases, what about the failing test case is different than the other test cases
    • As you walk through your program are the intermediate results as expected? You are trying to figure out where something went wrong, so if an intermediate result is wrong, the logical error happened earlier than that intermediate result.