Aussie AI
Debugging Techniques
-
Book Excerpt from "Generative AI in C++"
-
by David Spuler, Ph.D.
Debugging Techniques
The term “debugging” mainly refers to the process whereby a programmer tries to find the cause of a bug. Debugging is only part of the code reliability puzzle. A lot of other important techniques are involved in improving overall code reliability for the long-term, rather than how to quickly find and fix a known bug, which this chapter discusses.
The best debugging technique really depends on the symptoms of the bug, and on your experience and intuition telling you what type of coding error is likely. Some of the practical techniques to find a bug include:
- Interactive debugger tools (e.g. stepping through code in the Windows IDE or Gnu
gdb
on Linux). - Postmortem debugging (e.g. using
gdb
if you have a Linux core dump file). - Review compiler warnings for bugs hiding in plain sight.
- Enable more debug trace statements.
- Add some more assertions, unit tests, or self-testing code.
- Memory debugging tools (e.g. run the code in Valgrind on Linux).
Very Difficult Bugs. Some bugs are like roaches and keep coming out of the woodwork. General strategies for solving a tricky bug include:
- Can you reproduce it? That's the key.
- Write a unit test that triggers it (if you can).
- Gather as much information about the context as possible (e.g. if it's a user-reported error).
- Think about what code you just changed recently (or was just committed by someone else).
- Try to cut down the input to the smallest case that triggers the fault.
- Memory-related failures often cause weird errors nowhere near the cause.
- Review the debug trace output carefully (i.e. maybe something failed earlier).
- Step through the code in the debugger about ten more times.
- Run a static analysis (“linter”) tool on the code.
- Run an AI copilot debugger tool. I hear they're terrific.
- Refactor a large module into smaller functions that are more easily unit-tested (often you accidentally fix the bug!).
If you really get stuck, you could try talking to another human (gasp!). Show your code to someone else and they'll find the bug in three seconds.
Level Up Your Post-Debugging Routine. Assuming you can fix it, think about the next level of professionalism to avoid having a repetition of similar problems. Consider doing followups such as:
- Add a unit test or regression test to re-check that problematic input every build.
- Write it up and close the incident in the bug tracking database like a Goody Two-Shoes.
- Add safety input validation tests so that a similar failure is tolerated (and logged).
- Add a self-check in a C++ debug wrapper function to check for it next time at runtime.
- Is there a tool that would have found it? Can you run it automatically? Every build?
• Next: • Up: Table of Contents |
The new AI programming book by Aussie AI co-founders:
Get your copy from Amazon: Generative AI in C++ |