Page 1DebuggingApril 6, 2004DebuggingApril 6, 2004TopicsTopics Defensive programming Know your bugs Debugging Tricks Overview of available tools15-213“The course that gives CMU its Zip!”class23.ppt– 2 –15-213, S’04Defensive ProgrammingDefensive Programming55--20 Bugs per 1000 lines of code (InfoWorld, Oct. 2003)20 Bugs per 1000 lines of code (InfoWorld, Oct. 2003)Programmers must anticipate bugs, even if Programmers must anticipate bugs, even if youryourcode is bugcode is bug--free.free.How?How? Check for errors at all possible opportunities: detecting bugs early eases finding the root cause. Maintain a clean, modular structure with documented interfaces: goto’s, global variables, long-jumps, clever/obscure macros, etc. considered harmful dangerous. Anticipate common errors: buffer overrun, off-by-one,… Consider corner cases: 0/1 loops, empty lists, … Provide debugging support in your program: debugging messages, data structure checkers (like the Heap-checker from the malloc-lab), print-function for complicated structures, test-case generators, … Add redundancy Maintain test cases for regression testing: use version control systems (CVS, RCS, BitKeeper, Subversion, …) Use all the help you can get: heed compiler warnings, use debuggers, verifyers, IDE’s, code generators, high-level tools,…– 3 –15-213, S’04AssertionsAssertionsExplicitly state what you expect to be true in your Explicitly state what you expect to be true in your program: invariants, argument ranges, etc.program: invariants, argument ranges, etc.AssertAssert--macro (ISO9899, ANSI C):macro (ISO9899, ANSI C):Generates no tests if “NODEBUG” is defined#include <assert.h>#define MAX_ARRAY_SIZE 10void foo(double a[], double b[], int n){ int i;double *a_ptr = a, *b_ptr = b;assert(n > 1 && n <= MAX_ARRAY_SIZE);for (i = n; --i;) {/* ... */a_ptr++;/* ... */b_ptr++;}assert(a_ptr == &(a[n]) && b_ptr == &(b[n]));}– 4 –15-213, S’04Debug MessagesDebug MessagesUse of Use of cppcpp--macros and conditional compilation:macros and conditional compilation:#ifdef DEBUGextern int debug_level;#define DEBUG_PRINT(level, format, args...) \{ if((level) < debug_level) {\fprintf(stderr, "BEBUG_PRINT line=%d in file='%s':\n",\__LINE__, __FILE__);\fprintf(stderr, format , ## args);}\}#else#define DEBUG_PRINT(level, format, args...)#endiffoo(int a, int b) {DEBUG_PRINT(0, "foo(a=%d, b=%d) started\n", a, b);}Page 2– 5 –15-213, S’04Add RedundancyAdd RedundancyEngineering tradeoff between robustness and Engineering tradeoff between robustness and performance.performance.Extreme case Google:Extreme case Google: Data structures have software maintained checksums Distributed system (> 10,000 machines): need fail-stop characteristic, handle failures at higher levelSimple Cases:Simple Cases: Count item and compare to pointer difference (see assertion example) Compute simple, inexpensive invariants (for example: the sum of allocated and free memory objects in the heap ought to equal the heap size)– 6 –15-213, S’04Integrated Development EnvironmentIntegrated Development EnvironmentProgramProgram--editor (with syntax support), version control editor (with syntax support), version control system, compiler, debugger, buildsystem, compiler, debugger, build--system, profiler, system, profiler, graphical user interface, and integration = IDEgraphical user interface, and integration = IDE Microsoft Visual-* IBM’s Eclipse project Kdevelop (open source) Pro: convenience Con: often platform dependent No silver bullet– 7 –15-213, S’04Debugging HistoryDebugging HistoryIn 1945 G. Hopper found the first “bug” in IBM’s In 1945 G. Hopper found the first “bug” in IBM’s Harvard Mark IHarvard Mark I, an electro, an electro--mechanical computer:mechanical computer:– 8 –15-213, S’04Early DebuggingEarly DebuggingUse of front Use of front pannelpannelswitches & lights:switches & lights:Other tools included:Other tools included: Core dumps Print statements Hardware monitors SpeakersPage 3– 9 –15-213, S’04Know your BugsKnow your BugsCommon bugs in CCommon bugs in C--programsprograms Pointer bugs Dynamic memory allocation / deallocation bugs Memory leaks (missing free()calls) Buffer overflow bugs Arrays out of bound errors (off-by-one) Exception handling Variable scope problems (see linking lecture) Race conditions in multi-threaded codesOther bugs not considered in this class:Other bugs not considered in this class: Specification errors Performance bugs Program logic errors (bad algorithms, data structures, etc.)– 10 –15-213, S’04Encounter with a BugEncounter with a BugProgram produces unexpected result and/or crashesProgram produces unexpected result and/or crashes Is this behavior reproducible? Does it depend on input data? Does it change with compilation options? (-g vs. –O2)First goal: narrow the possible code range that could be First goal: narrow the possible code range that could be responsible for the bug:responsible for the bug: Divide & Conquer Simplify the code that shows the bug In case of rare/intermittent bugs: try to cause the program to fail more frequently Add logging or debugging printouts to pinpoint the approximate location of the failure– 11 –15-213, S’04GDB (GNU DeBugger)GDB (GNU DeBugger)Basic functionality:Basic functionality: Can run programs in an observable environment Uses ptrace-interface to insert breakpoint, single step, inspect & change registers and variables Does not require compilation with “-g”, but works much better if it has the symbol tables available Maintains source line numbers and can inspect source files Ability to attach to a running process Ability to watch memory locations Conditional breakpoints Some graphical user interfaces exist (DDD, KDbg, …)– 12 –15-213, S’04DDDDDDGraphical frontGraphical front--end to GDB with extended data end to GDB with extended data visualization support: http://visualization support: http://www.gnu.org/software/dddwww.gnu.org/software/dddPage 4– 13 –15-213, S’04Annoyingly Frequent Case:Annoyingly Frequent Case:Memory corruption due to an earlier pointer or dynamic Memory corruption due to an earlier pointer or dynamic memory allocation error: bug cause and effect are memory allocation error: bug cause and effect are separated by 1000’s
View Full Document