1 Debugging The material for this lecture is drawn, in part, from The Practice of Programming (Kernighan & Pike) Chapter 5 Professor Jennifer Rexford

Slides:



Advertisements
Similar presentations
CS 450 Module R1. R1 Introduction In Module R1, you will implement a user interface (command handler). There are a couple of options: ▫Command Line: interface.
Advertisements

Debugging What can debuggers do? Run programs Make the program stops on specified places or on specified conditions Give information about current variables’
1 Memory Allocation Professor Jennifer Rexford COS 217.
CS 326 Programming Languages, Concepts and Implementation Instructor: Mircea Nicolescu Lecture 18.
Chapter 8 Runtime Support. How program structures are implemented in a computer memory? The evolution of programming language design has led to the creation.
Debugging Introduction to Computing Science and Programming I.
Strings and Dynamic Memory Allocation CS-2301, B-Term Programming Assignment #6 Strings and Dynamic Memory Allocation CS-2301, System Programming.
1 Debugging The material for this lecture is drawn, in part, from The Practice of Programming (Kernighan & Pike) Chapter 5.
Environment & tools Assistant Anssi Jääskeläinen Visiting hours: Tuesdays Room: 6606
If You Missed Last Week Go to Click on Syllabus, review lecture 01 notes, course schedule Contact your TA ( on website) Schedule.
CSE 303 Lecture 13a Debugging C programs
Guide To UNIX Using Linux Third Edition
C Programming. C vs C++ C syntax and C++ syntax are the same but... C is not object oriented * There is no string class * There are no stream objects.
Debugger Presented by 李明璋 2012/05/08. The Definition of Bug –Part of the code which would result in an error, fault or malfunctioning of the program.
JS Arrays, Functions, Events Week 5 INFM 603. Agenda Arrays Functions Event-Driven Programming.
Homework Reading Programming Assignments
CS3012: Formal Languages and Compilers The Runtime Environment After the analysis phases are complete, the compiler must generate executable code. The.
CS 11 C track: lecture 5 Last week: pointers This week: Pointer arithmetic Arrays and pointers Dynamic memory allocation The stack and the heap.
Hank Childs, University of Oregon May 15th, 2015 CIS 330: _ _ _ _ ______ _ _____ / / / /___ (_) __ ____ _____ ____/ / / ____/ _/_/ ____/__ __ / / / / __.
9 Chapter Nine Compiled Web Server Programs. 9 Chapter Objectives Learn about Common Gateway Interface (CGI) Create CGI programs that generate dynamic.
1 ENERGY 211 / CME 211 Lecture 13 October 20, 2008.
Compiling & Debugging Quick tutorial. What is gcc? Gcc is the GNU Project C compiler A command-line program Gcc takes C source files as input Outputs.
Creating your first C++ program
1 C - Memory Simple Types Arrays Pointers Pointer to Pointer Multi-dimensional Arrays Dynamic Memory Allocation.
Testing and Debugging Version 1.0. All kinds of things can go wrong when you are developing a program. The compiler discovers syntax errors in your code.
Introduction to Exception Handling and Defensive Programming.
C Programming in Linux Jacob Chan. C/C++ and Java  Portable  Code written in one system and works in another  But in C, there are some libraries that.
CSE 232: C++ debugging in Visual Studio and emacs C++ Debugging (in Visual Studio and emacs) We’ve looked at programs from a text-based mode –Shell commands.
CSE 332: C++ debugging Why Debug a Program? When your program crashes –Finding out where it crashed –Examining program memory at that point When a bug.
1 Debugging (Part 1) The material for this lecture is drawn, in part, from The Practice of Programming (Kernighan & Pike) Chapter 5.
CSE 351 GDB Introduction. Lab 1 Status? How is Lab 1 going? I’ll be available at the end of class to answer questions There are office hours later today.
1 CSE306 Operating Systems Projects CVS/SSH tutorial.
1 Debugging and Syntax Errors in C++. 2 Debugging – a process of finding and fixing bugs (errors or mistakes) in a computer program.
CSE 374 Programming Concepts & Tools Hal Perkins Fall 2015 Lecture 11 – gdb and Debugging.
© Janice Regan, CMPT 128, February CMPT 128: Introduction to Computing Science for Engineering Students Pointers.
12 CVS Mauro Jaskelioff (originally by Gail Hopkins)
CSE 374 Programming Concepts & Tools Hal Perkins Fall 2015 Lecture 10 – C: the heap and manual memory management.
1 Homework Done the reading? –K&R –Glass Chapters 1 and 2 Applied for cs240? (If not, keep at it!) Gotten a UNIX account? (If not, keep at it!)
PROGRAM ESSENTIALS. TOKENS  SMALLEST UNITS OF A PROGRAM LANGUAGE  Special Symbols  Mathematical Operators  Punctuation  Word Symbols  Key Words.
17/02/2016S. Ponce / EP-LBC1 Debugging Under Linux Sebastien Ponce Friday, 8 March 2002.
1 Debugging (Part 2). “Programming in the Large” Steps Design & Implement Program & programming style (done) Common data structures and algorithms Modularity.
Announcements Assignment 1 due Wednesday at 11:59PM Quiz 1 on Thursday 1.
Recitation 2: Abhijit Warkhedi2/25/20161 Today’s Agenda u CVS u GDB.
Debugging: Tips and Tools Also, Aloha Recitation Wednesday, February 7th, 2007.
CMPSC 16 Problem Solving with Computers I Spring 2014 Instructor: Lucas Bang Lecture 11: Pointers.
CSE 332: C++ expressions Expressions: Operators and Operands Operators obey arity, associativity, and precedence int result = 2 * 3 + 5; // assigns 11.
CSE 303 Concepts and Tools for Software Development Richard C. Davis UW CSE – 10/11/2006 Lecture 7 – Introduction to C.
L071 Introduction to C Topics Compilation Using the gcc Compiler The Anatomy of a C Program Reading Sections
Hank Childs, University of Oregon April 15 th, 2016 CIS 330: _ _ _ _ ______ _ _____ / / / /___ (_) __ ____ _____ ____/ / / ____/ _/_/ ____/__ __ / / /
DYNAMIC MEMORY ALLOCATION. Disadvantages of ARRAYS MEMORY ALLOCATION OF ARRAY IS STATIC: Less resource utilization. For example: If the maximum elements.
DEBUG.
Memory-Related Perils and Pitfalls in C
Object Lifetime and Pointers
Winter 2009 Tutorial #6 Arrays Part 2, Structures, Debugger
CSE 374 Programming Concepts & Tools
CSE 374 Programming Concepts & Tools
Testing and Debugging.
Functions and Structured Programming
Hank Childs, University of Oregon
Common C Programming Errors, GDB Debugging
Debugging Jennifer Rexford
Tonga Institute of Higher Education
CSE 403 Lecture 17 Coding.
When your program crashes
Homework Applied for cs240? (If not, keep at it!) 8/10 Done with HW1?
Robust Coding and Debugging
An Overview of C.
CSE 303 Concepts and Tools for Software Development
Debugging.
CSE 303 Concepts and Tools for Software Development
Presentation transcript:

1 Debugging The material for this lecture is drawn, in part, from The Practice of Programming (Kernighan & Pike) Chapter 5 Professor Jennifer Rexford

2 Goals of this Lecture Help you learn about: Strategies for debugging your code The GDB debugger The RCS version control system Why? Debugging large programs can be difficult A power programmer knows a wide variety of debugging strategies A power programmer knows about tools that facilitate debugging Debuggers Version control systems

3 Testing vs. Debugging Testing What should I do to try to break my program? Debugging What should I do to try to fix my program?

4 Debugging Heuristics Debugging HeuristicWhen Applicable (1) Understand error messagesBuild-time (2) Think before writing Run-time (3) Look for familiar bugs (4) Divide and conquer (5) Add more internal tests (6) Display output (7) Use a debugger (8) Focus on recent changes

5 Understand Error Messages Debugging at build-time is easier than debugging at run- time, if and only if you… (1) Understand the error messages!!! Some are from the preprocessor #include int main(void) /* Print "hello, world" to stdout and return 0. { printf("hello, world\n"); return 0; } $ gcc217 hello.c -o hello hello.c:1:20: stdioo.h: No such file or directory hello.c:3:1: unterminated comment hello.c:2: error: syntax error at end of input Misspelled #include file Missing */

6 Understand Error Messages (cont.) (1) Understand the error messages (cont.) Some are from the compiler #include int main(void) /* Print "hello, world" to stdout and return 0. */ { printf("hello, world\n") retun 0; } $ gcc217 hello.c -o hello hello.c: In function `main': hello.c:7: error: `retun' undeclared (first use in this function) hello.c:7: error: (Each undeclared identifier is reported only once hello.c:7: error: for each function it appears in.) hello.c:7: error: syntax error before numeric constant Misspelled keyword

7 Understand Error Messages (cont.) (1) Understand error messages (cont.) Some are from the linker #include int main(void) /* Print "hello, world" to stdout and return 0. */ { prinf("hello, world\n") return 0; } $ gcc217 hello.c -o hello hello.c: In function `main': hello.c:6: warning: implicit declaration of function `prinf' /tmp/cc43ebjk.o(.text+0x25): In function `main': : undefined reference to `prinf' collect2: ld returned 1 exit status Misspelled function name Compiler warning (not error): prinf() is called before declared Linker error: Cannot find definition of prinf()

8 Think Before Writing Inappropriate changes could make matters worse, so… (2) Think before writing Draw pictures of the data structures Update pictures as the algorithms change data structures Take a break Sleep on it! Start early so you can!!! Explain the code to: Yourself Someone else A teddy bear A giant wookie

9 Look for Familiar Bugs (3) Look for familiar bugs Some of our favorites: int i; … scanf("%d", i); char c; … c = getchar(); switch (i) { case 0: … /* missing break */ case 1: … break; … } if (i = 5) … if (5 < i < 10) … if (i & j) … while (c = getchar() != EOF) … Note: enabling warnings will catch some (but not all) of these

10 Divide and Conquer (4) Divide and conquer Eliminate input Incrementally find smallest/simplest input that illustrates the bug Example: Program fails on large input file filex Make copy of filex named filexcopy Delete 2 nd half of filexcopy Run program on filexcopy Program works => 1 st half of filex does not illustrate bug, so discard 1 st half and keep 2 nd half Program fails => 1 st half of filex illustrates bug, so keep 1 st half and discard 2 nd half Recurse until no lines of filex can be discarded Alternative: Start with small subset of filex, and incrementally add lines until bug appears

11 Divide and Conquer (cont.) (4) Divide and conquer (cont.) Eliminate code Incrementally find smallest code subset that illustrates the bug Example: Test client for your module fails In test client, comment out calls of some function Or in your module, create stub definition of some function Run test client Bug disappears => it’s in commented-out code Bug remains => it’s in remaining code, so repeat for another function

12 Add More Internal Tests (5) Add more internal tests (See “Testing” lecture) Internal tests help finding bugs Internal test also can help eliminate bugs Checking invariants and conservation properties can eliminate some functions from the bug hunt

13 Display Output (6) Display output Print values of important variables at critical spots Poor: Maybe better: Better: printf("%d", keyvariable); stdout is buffered; program may crash before output appears printf("%d", keyvariable); fflush(stdout); printf("%d\n", keyvariable); Call fflush() to flush stdout buffer explicitly Printing '\n' flushes the stdout buffer, but not if stdout is redirected to a file

14 Display Output (cont.) (6) Display output (cont.) Maybe even better: Maybe better still: fprintf(stderr, "%d", keyvariable); FILE *fp = fopen("logfile", "w"); … fprintf(fp, "%d", keyvariable); fflush(fp); Write debugging output to stderr; debugging output can be separated from normal output via redirection Write to a log file Bonus: stderr is unbuffered

15 Use a Debugger (7) Use a debugger Bugs often are the result of a flawed mental model; debugger can help correct mental model Sometimes (but not always) debugger is more convenient than inserting printing statements Debugger can load “core dumps” and let you step through state of program when it died Can “attach” to running programs to examine execution The GDB Debugger Part of the GNU development environment Integrated with XEMACS editor

16 Using GDB An example program File testintmath.c: #include int gcd(int i, int j) { int temp; while (j != 0) { temp = i % j; i = j; j = temp; } return i; } int lcm(int i, int j) { return (i / gcd(i, j)) * j; } … The program is correct But let’s pretend it has a runtime error within gcd()… … int main(void) { int iGcd; int iLcm; iGcd = gcd(8, 12); iLcm = lcm(8, 12); printf("%d %d\n", iGcd, iLcm); return 0; } Euclid’s algorithm

17 Using GDB (cont.) General GDB strategy: Execute the program to the point of interest Use breakpoints and stepping to do that Examine the values of variables at that point

18 Using GDB (cont.) Typical steps for using GDB: (1) Build with –g gcc217 –g testintmath.c –o testintmath Adds extra information to executable file that GDB uses (2) Run Emacs, with no arguments emacs (3) Run GDB on executable file from within Emacs x gdb testintmath (4) Set breakpoints, as desired break main GDB sets a breakpoint at the first executable line of main() break gcd GDB sets a breakpoint at the first executable line of gcd()

19 Using GDB (cont.) Typical steps for using GDB (cont.): (5) Run the program run GDB stops at the breakpoint in main() XEMACS opens window showing source code XEMACS highlights line that is to be executed next continue GDB stops at the breakpoint in gcd() XEMACS highlights line that is to be executed next (6) Step through the program, as desired step (repeatedly) GDB executes the next line (repeatedly) Note: When next line is a call of one of your functions: step command steps into the function next command steps over the function, that is, executes the next line without stepping into the function

20 Using GDB (cont.) Typical steps for using GDB (cont.): (7) Examine variables, as desired print i print j print temp GDB prints the value of each variable (8) Examine the function call stack, if desired where GBB prints the function call stack Useful for diagnosing crash in large program (9) Exit gdb quit (10) Exit xemacs

21 Using GDB (cont.) GDB can do much more: Handle command-line arguments run arg1 arg2 Handle redirection of stdin, stdout, stderr run someotherfile Print values of expressions Break conditionally Etc. See Programming with GNU Software (Loukides and Oram) Chapter 6

22 Focus on Recent Changes (8) Focus on recent changes Corollary: Debug now, not later Difficult: Write entire program; test entire program; debug entire program Easier: Write a little; test a little; debug a little; write a little; test a little; debug a little; … Corollary: Maintain previous versions Difficult: Change code; note bug; try to remember what changed since last working version!!! Easier: Backup code; change code; note bug; compare new version with last working version to determine what changed

23 Maintaining Previous Versions To maintain previous versions Approach 1: Manually copy project directory Repeat occasionally Approach 2: Use RCS… … $ mkdir myproject $ cd myproject Create project files here. $ cd.. $ cp –r myproject myprojectDateTime $ cd myproject Continue creating project files here. …

24 RCS RCS (Revision Control System) A simple personal version control system Provided with many Linux distributions Provided on hats Appropriate for one-developer projects Better choices for multi-developer projects: CVS Subversion

25 Using RCS Typical steps for using RCS: (1) Create project directory, as usual mkdir helloproj cd helloproj (2) Create RCS directory in project directory mkdir RCS RCS will store its repository in that directory (3) Create source code files in project directory xemacs hello.c … (4) Check in ci hello.c Adds file to RCS repository Deletes local copy (don’t panic!) Can provide description of file (1 st time) Can provide log message, typically describing changes

26 Using RCS (cont.) Typical steps for using RCS (cont.): (5) Check out most recent version for reading co hello.c Copies file from repository to project directory File in project directory has read-only permissions (6) Check out most recent version for reading/writing co –l hello.c Copies file from repository to project directory File in project directory has read/write permissions (7) List versions in repository rlog hello.c Shows versions of file, by number (1.1, 1.2, etc.), with descriptions (8) Check out a specified version co –l –rversionnumber hello.c

27 Using RCS (cont.) RCS can do much more: Merge versions of files Maintain distinct development branches Place descriptions in code as comments Assign symbolic names to versions Etc. See Programming with GNU Software (Loukides and Oram) Chapter 8 Recommendation: Use RCS “ci” and “co” can become automatic!

28 Summary * Use GDB ** Use RCS Debugging HeuristicWhen Applicable (1) Understand error messagesBuild-time (2) Think before writing Run-time (3) Look for familiar bugs (4) Divide and conquer (5) Add more internal tests (6) Display output (7) Use a debugger * (8) Focus on recent changes **

29 Appendix: Debugging Mem Mgmt Some debugging techniques are specific to dynamic memory management That is, to memory managed by malloc(), calloc(), realloc(), and free() Will be pertinent soon in course For future reference…

30 The Rest of This Week Reading Required: King book: chapters 8, 9, 11, 12, and 13 Recommended: Kernighan and Pike: chapters 5 and 6 Recommended: GNU Software: chapter 8 Assignment #2 One-week assignment on String Module Due 9pm Sunday February 22 Checking your understanding of the first two weeks Try questions 1, 3e, 4, and 6 of the Spring 2008 midterm Questions: 1/spring08-cos217-exam1.pdf 1/spring08-cos217-exam1.pdf Answers: 1/spring08-cos217-exam1-answers.pdf 1/spring08-cos217-exam1-answers.pdf

31 Appendix: Debugging Mem Mgmt (9) Look for familiar dynamic memory management bugs Some of our favorites: int *p; /* value of p undefined */ … *p = somevalue; int *p; /* value of p undefined */ … fgets(p, 1024, stdin); Dangling pointer int *p; … p = (int*)malloc(sizeof(int)); … free(p); … *p = 5; Dangling pointer

32 Appendix: Debugging Mem Mgmt (9) Look for familiar dynamic memory management bugs (cont.) Some of our favorites (cont.): int *p; … p = (int*)malloc(sizeof(int)); … p = (int*)malloc(sizeof(int)); … Memory leak alias Garbage creation Detection: valgrind, etc. int *p; … p = (int*)malloc(sizeof(int)); … free(p); … free(p); Multiple free Detection: man malloc, MALLOC_CHECK_

33 Appendix: Debugging Mem Mgmt (9) Look for familiar dynamic memory management bugs (cont.) Some of our favorites (cont.): char *s1 = "Hello"; char *s2; s2 = (char*)malloc(strlen(s1)); strcpy(s2, s1); double *p; p = (double*)malloc(sizeof(double*)); char *s1 = "Hello"; char *s2; s2 = (char*)malloc(sizeof(s1)); strcpy(s2, s1); Allocating too few bytes Avoidance: strdup Allocating too few bytes Avoidance: alloca

34 Appendix: Debugging Mem Mgmt (10)Segmentation fault? Make it happen within gdb, and then issue the gdb where command. The output will lead you to the line that caused the fault. (But that line may not be where the error resides.) (11)Call assert() to make sure value returned by malloc(), calloc(), and realloc() is not NULL. (12)Manually inspect each call of malloc(), calloc(), and realloc() in your code, making sure that it allocates enough memory. (13)Temporarily hardcode each call of malloc(), calloc(), and realloc() such that it requests a large number of bytes. If the error disappears, then you'll know that at least one of your calls is requesting too few bytes.

35 Appendix: Debugging Mem Mgmt (14) Temporarily comment-out each call of free() in your code. If the error disappears, then you'll know that you're freeing memory too soon, or freeing memory that already has been freed, or freeing memory that should not be freed, etc. (15)Use the Meminfo tool. Programs built with gcc217m are much more sensitive to dynamic memory management errors than are programs built with gcc217. So the error might manifest itself earlier, and thereby might be easier to diagnose.