Debugging 101

Tips to help you find bugs.

Turn the warning level up and turn on warnings as errors
I know, it can be a pain, but it works. It helps you produce more rhobust, forward compatible, portable code that is syntactically correct on more compilers.
Use assert …
Assert will help you find errors before you even knew there was a problem. It is 100x better if your application tells you exactly where problems are and breaks into the debugger than for your application to crash for the customer. It goes hand in hand with compile time type safety, compiler warnings and static_assert.
… and use if () return
Think of assert as flagging the problem for you to fix and if () return as guarding the application from crashing for the customer.
Print to your errors/trace file
It can be easier to read what the application did rather than stepping through it, in some cases it is not possible to step through the code at all; full screen games, embedded devices and drivers for example. Print out variables, function entrance/exit and “I am here” lines.
Comment out or remove as much code as possible. Slowly remove lines until you find the offending line. Try different ways of doing the same thing. Read your errors/trace file. If I had a dollar for every time a coworker tells me there is a bug in the library/standard library/compiler/Operating System and it is actually an error in their code and they have ignored a printed error, I would buy a Ferrari, and then I would buy them a pair of spectacles and I would say, “Use these to read these”, and point at the error message.
Write data to files and validate your files
For example XML, HTML, JSON, RSS, KML, PNG, WAV and MP3, can all be written to files and run through third party validation software. You can even setup a unit test to write these to a file and run the validator for you.
Use your debugger
Put break points on suspect lines, step through functions, find out the value of variables, look at what each thread is doing, look at the call stack.
Read the documentation for the library you are using
You may be using a library incorrectly, it may have conditions or prerequisites you didn’t know about. If it is too complex wrap it into something easier to digest. If its usage is error prone wrap it into something simpler and type safe, that only uses what you need. An optimising compiler will factor out your wrapper and it will have no run time impact.
It is there for a reason. Millions of developers have used it for almost two decades, hundreds of thousands of eyes have pored over the source code to it. Chances are that it is more capable, less bug ridden and more portable than your hodge podge collection of classes. A large percentage of bugs I have seen are in classes that could be replaced by the STL. Plus developers will “just know” what your code does because they already have experience with STL. Just use it.

Leave a Reply

Your email address will not be published. Required fields are marked *