Binary search if cause is far away

I talked about debugging as binary search.

What if the problem is caused far away, and the symptom shows up later? For example, in the following example, suppose function1() inadvertently writes beyond the end of buffer[] and breaks the value of globalp.

    char buffer[128];
    char* globalp;
    function1() { ... }
    function2() { ... }

Later the other function2() uses globalp and goes south. This type of bug is one of the hardest to find. First, the OK-NG chart goes likes this:

                |<--function1-->|             |<--function2-->|

There are two reasons why this type of buf is hard. By knowing the nature of the hardness, we may be able to better handle the bug.

The first reason is the OK point. We don’t know when the OK condition is disturbed. So we cannot start the binary search yet.

The second reason is the NG point. In this case the NG point is not where the real bug is. Instead, it is where the symptom appears, such as segmentation fault. But because it is the only reference point, we have to treat it as an initial NG point, and we should not forget that the real bug is not there.

First, we have to look into the NG point closely and see what is causing the symptom, such as segmentation fault. Once we find that globalp is pointing wrong place, we can rewrite the OK-NG chart.

                |<--function1-->|             |<--function2-->|

The chart looks exactly same as before. But it has different meaning. NG is where globalp is pointing wrong place. OK is where globalp is sane. Now we can start the bianry search just by looking at the value of globalp.

The important thing is, when you draw the first OK-NG chart in your mind, you should know that it is only temporary. And you should do what ever to take you to the second OK-NG chart.