Date: Tue, 28 Nov 2000 14:40:07 -0800 (PST) From: Hannah C. Tang To: cse142-section-bf@cs.washington.edu Subject: [Section BF] Off-by-one In section, I've discussed how one of the two most common C programming errors (uninitialized pointers/variables) caused a fatal bug in a program which was being developed at the company I spent my internship at. As you're working on HW 5, please keep in mind the second most common error: iterating past the end of an array. Keep an eye on your loop conditions, and remember that arrays are zero-indexed. That is, if you're trying to initialize an array to zero, your loop conditions should look like: for(index = 0; index < ARRAY_SIZE; index++) { myArray[index] = 0; } Or: for(index = 1; index <= ARRAY_SIZE; index++) { myArray[index - 1] = 0; } Note the loop initialization and termination conditions. The two other possible combinations of these initialization/termination conditions are off by one, and will result in a bug in your program. /* This will write a zero at the memory location immediately * following the array (who knows what might be there?) -- which * is an off-by-one error */ for(index = 0; index <= ARRAY_SIZE; index++) { myArray[index] = 0; } /* This will NOT write a zero at the last index of the * array, leaving you with an uninitialized value -- which * is again an off-by-one error */ for(index = 1; index < ARRAY_SIZE; index++) { myArray[index - 1] = 0; } Hannah (Side note: Just last week, it took me 2 days to chase down a combination of the two errors. I wrote past the end of an array -- and the next memory location contained a pointer)