Wednesday, October 21, 2009

Section 3.1.  The Next Step










3.1. The Next Step


In Chapter 2, we got the Linrg command line tool to build without errors and used the Xcode debugger passively to track down and eliminate an early crashing bug. Let's run our tool again and see how it goes. Make sure that the project is built, and select Debug Executable from the Build and Go menu in the Project window's toolbar.


Once again, we select Standard I/O Log from the Debug menu, so we can interact with Linrg. Type some data:


   1.0  2.05
nan nan nan


Well, after we enter two numbers and press Return, Linrg does not crash. It simply prints nan nan nan and quits. The status bar in the Debugger and Project windows says, "Debugging of Executable 'Linrg' ended normally."


Something else is wrong. An illegal floating-point operationsuch as dividing 0 by 0, or square-rooting a negative numbertook place somewhere in our calculations, resulting in a NaN (not a number), the special float value that signals an illegal operation. This need have happened only once; any arithmetic done with a NaN results in a NaN, so a single illegal operation early in the process could propagate the invalid-result marker through all subsequent calculations.


It makes sense that Linrg should report indeterminate results: Apparently, it tried to compute the regression line after reading only one point, which is not enough to determine a line. We suspect that this problem, then, is not in the computations but in the early exit from the input loop.


The time-honored way to track down a bug like this is to put a printf() call after every calculation, so that the problem code shows the state of the program at each significant step. If the right things are printed at the right time, you can see where the application went off the rails.


There is no need to instrument a step-by-step picture of Linrg's state, however, because we have a computer to take care of that for us. The Xcode debugger will do everything we need.












No comments: