1.1 Example

We elaborate the systematic debugging approach by a concrete example implementing a stack. The program is given in Section 3 including the Stack class plus a main function providing an interactive console interface to play with an instance of Stack.



Figure 1: A run for testing stack class in section 1.1.

PIC


If you run the given main function in Section 3, and test it by entering a number of pushes and asking for the ‘sum’, you will see an in correct result. For example, Figure 1 shows the sum after two pushes. Hence, there might be an error in Stack class that has to be resolved. Since the code was compiled perfectly, syntax error is not plausible and the error has to be logical. We start debugging the logical error by proposing hypothesis 1.

Hypothesis 1. Since the sum function returns incorrect value, it might be implemented inaccurately.

Predication
sum does not consider all the elements in the stack. The iterators bound in the sum function is not adjusted correctly.
Experiment
To evaluate the predication, we can look at the code and see the iterator in the sum function is exactly similar to one in the operatorˇˇ function. Thus, if we print the the stack, all items that sum calculates their sum are printed on the screen.
Observation
The output of print function starts from 0 and ends an item pushed before the last item.
Conclusion
The hypothesis is rejected.

Since hypothesis 1 is rejected, we have to bring up another hypothesis and evaluate it.

Hypothesis 2. Push does not insert the first item in the beginning of the array.

Predication
Push starts to insert the items into the array from index 1 instead of 0.
Experiment
The predication is evaluated by printing the stack after each push.
Observation
The output of print function starts from 0, but the first item is something different.
Conclusion
The hypothesis is confirmed.

Hypothesis 2 is correct, now it has to be refined into a more precise hypothesis revealing the root of the problem and a way to fix it.

Hypothesis 3. The index showing the first available empty spot in increased before the item is inserted.

Predication
array[ ++size ] = v has to be replaced with array[ size++ ] = v
Experiment
The predication is evaluated by printing the stack after each push.
Observation
The output of print function starts from the first item pushed in the stack
Conclusion
The hypothesis is confirmed.

Based on hypothesis 3, we fixed the bug.