Debugging
Interesting anecdote: most programmers spend more time debugging than writing code!
Steps to debugging
- Determine that you have a bug
- Isolate the bug's location
- Find the culprit code
Identifying a bug
- In order to find a bug, lots and lots of testing
- Answer the question: what is the behaviour that you think is buggy (in words).
- Why do you think that the behaviour is buggy?
- Differs from given expected output?
- Not what you were expecting, e.g., too slow, too much memory consumption, crashes, runs out of resources, never finishes, ...
- Try to pinpoint: under what circumstances does the bug appear
- Try different inputs or outputs
- Goal: find the smallest input possible that reproduces the bug!
- Be specific, and keep getting more specific until you find the issue!
There are many different strategies possible (the one detailed above is just one of them)
- Goal: Where in the code could the bug be? e.g., everything was working fine yesterday but something went wrong today, so perhaps the code written today is the first suspect
- Be creative: better to think of too many places than too few
- Like a detective game. Can be quite fun when you find the issue
- Example: Identify different functions that could be the culprit
- Then run each function separately (need to construct inputs to the function)
- Print out parameters and return values
- Use the debugger! e.g.,
gdb
. See next week's lab assignment.
Finding the bug
- Once you have found the function, need to find the bug
- What does each line of code do?
- Use print statements or the debugger to verify your assumptions
- Explain each line of code to your partner or to an imaginary person
- Draw pictures - keep track of values in data structures and variable values
Using the debugger
Some common functionalities in a debugger