Disclaimer: I suspect that this post won’t be useful to anyone who really knows how to debug a program — but hey, the procedure I describe is so simple, and has no learning curve!
I am a novice C++ programmer. Recently, I’ve been using a simple trick to see which portions of my code are being accessed or not. Simply include the cassert header in your code, like so:
Now, include the statement assert(0); in the part of your code that you suspect is causing your program to crash. The assert() macro aborts your program if the condition given is zero or false — so if we hard-code a failing argument, as in assert(0), your program will terminate consistently, upon executing that particular assert(0) statement.
The cool part: if your code executes the assert(0) statement, then that means that, up to that point in your code, your program worked perfectly fine. On the other hand, if you cannot get your program to abort with assert(0), this means that your program hangs or crashes before getting to the “assert(0)” statement ; thus, you can just move this “assert(0)” statement up (“up” as in an earlier point of time in the manner your code is executed), and repeat the procedure above to get closer to the bug.
So, for example, if you have a FOR loop, and inside this FOR loop, the first thing you put in is assert(0), and nothing happens, this means that the FOR loop isn’t even being executed at all! Similarly, simply put in assert(0) inside a function, to see whether that function is being called; if it IS being called, your program will abort with assert(0).
As a general practice, you could put in many assert() statements in your control flow code, so that they only execute if the statement inside assert() is true.