vi Contents
3 Prevent, Detect, and Remove Bugs 33
3.1 Developing Software =Coding ......................... 33
3.1.1 Beforecoding............................... 34
3.1.2 Duringcoding .............................. 34
3.1.3 Aftercoding ............................... 35
3.2 CommonMistakes ................................ 35
3.2.1 UninitializedVariables.......................... 36
3.2.2 WrongArrayIndexes .......................... 36
3.2.3 WrongTypes............................... 36
3.3 Post-ExecutionandInteractiveDebugging .................. 36
3.4 SeparateTestingCodefromProductionCode ................ 37
4Pointers 39
4.1 Scope ....................................... 39
4.2 TheSwapFunction ............................... 41
4.3 Pointers ...................................... 43
4.4 TheSwapFunctionRevisited .......................... 47
4.5 TypeErrors ................................... 50
4.6 ArraysandPointers ............................... 51
4.7 TypeRules .................................... 54
4.8 PointerArithmetic ................................ 55
4.9 Exercises ..................................... 59
4.9.1 SwapFunction1 ............................. 59
4.9.2 SwapFunction2 ............................. 59
4.9.3 SwapFunction3 ............................. 60
4.9.4 SwapFunction4 ............................. 60
4.9.5 SwapFunction5 ............................. 61
4.9.6 15,552Variations............................. 61
4.10Answers...................................... 62
4.10.1 SwapFunction1 ............................. 62
4.10.2 SwapFunction2 ............................. 63
4.10.3 SwapFunction3 ............................. 63
4.10.4 SwapFunction4 ............................. 63
4.10.5 SwapFunction5 ............................. 63
5 Writing and Testing Programs 65
5.1 DistinctArrayElements ............................ 65
5.1.1 main Function .............................. 66
5.1.2 areDistinct Function.......................... 67
5.1.3 Compiling and Linking . . . . . . . . . . . . . . . . . . . . . . . . . . 68
5.1.4 make .................................... 69
5.2 Test Using Makefile .............................. 71
5.2.1 GeneratingTestCases.......................... 72
5.2.2 RedirectingOutput ........................... 72
5.2.3 Use diff toCompareOutput...................... 73
5.2.4 Adding Tests to Makefile ........................ 73
5.3 Invalid Memory Access . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 75
5.4 Using valgrind to Check Memory Access Errors . . . . . . . . . . . . . . . 77
5.5 TestCoverage .................................. 79
5.6 LimitCoreSize ................................. 82
5.7 Programs with Infinite Loops . . . . . . . . . . . . . . . . . . . . . . . . . . 83