240-491 Adv. UNIX: debug/141 Advanced UNIX v Objectives of these slides: –tools and techniques for debugging C code 240-491 Special Topics in Comp. Eng.

Slides:



Advertisements
Similar presentations
CS 11 C track: lecture 7 Last week: structs, typedef, linked lists This week: hash tables more on the C preprocessor extern const.
Advertisements

Compilation and Debugging 101. Compilation in C/C++ hello.c Preprocessor Compiler stdio.h tmpXQ.i (C code) hello.o (object file)
C Language.
Recitation By yzhuang, sseshadr. Agenda Debugging practices – GDB – Valgrind – Strace Errors and Wrappers – System call return values and wrappers – Uninitialization.
Review of Scientific Programming in C and Fortran Michael McLennan Software Architect HUBzero™ Platform for Scientific Collaboration.
Debugging What can debuggers do? Run programs Make the program stops on specified places or on specified conditions Give information about current variables’
DEBUGGING IN THE REAL WORLD : Recitation 4.
Gdb: GNU Debugger Lecturer: Prof. Andrzej (AJ) Bieszczad Phone: “UNIX for Programmers and Users” Third Edition, Prentice-Hall,
David Notkin Autumn 2009 CSE303 Lecture 16 #preprocessor Debugging is twice as hard as writing the code in the first place. Therefore, if you write the.
. Compilation / Pointers Debugging 101. Compilation in C/C++ hello.c Preprocessor Compiler stdio.h tmpXQ.i (C code) hello.o (object file)
CSE 303 Lecture 13a Debugging C programs
Declaring Arrays Declare an array of 10 elements: int nums[10]; Best practice: #define SIZE 10 int nums[SIZE]; // cannot be int[SIZE] nums; C99: int nums[someVariable]
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.
C Slides and captured lecture (video and sound) are available at:
Debugging Logic Errors CPS120 Introduction to Computer Science Lecture 6.
Homework Reading –Finish K&R Chapter 1 (if not done yet) –Start K&R Chapter 2 for next time. Programming Assignments –DON’T USE and string library functions,
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.
Gdb is the GNU debugger on our CS machines. gdb is most effective when it is debugging a program that has debugging symbols linked in to it. With gcc and.
CS 11 C track: lecture 1 Preliminaries Need a CS cluster account cgi-bin/sysadmin/account_request.cgi Need to know UNIX ITS.
Homework Reading Programming Assignments
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.
C Tutorial Session #2 Type conversions More on looping Common errors Control statements Pointers and Arrays C Pre-processor Makefile Debugging.
1 Κατανεμημένες Διαδικτυακές Εφαρμογές Πολυμέσων Γιάννης Πετράκης.
1 C++ Classes and Data Structures Jeffrey S. Childs Chapter 4 Pointers and Dynamic Arrays Jeffrey S. Childs Clarion University of PA © 2008, Prentice Hall.
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.
Introduction to Programming
Agenda Attack Lab C Exercises C Conventions C Debugging
Adv. UNIX: Profile/151 Advanced UNIX v Objectives –introduce profiling based on execution times and line counts Special Topics in Comp.
1 SEEM3460 Tutorial Compiling and Debugging C programs.
C By Example 1 The assumption is that you know Java and need to extend that knowledge so you can program in C. 1. Hello world 2. declarations 3. pass by.
Topic 3: C Basics CSE 30: Computer Organization and Systems Programming Winter 2011 Prof. Ryan Kastner Dept. of Computer Science and Engineering University.
1 Debugging and Syntax Errors in C++. 2 Debugging – a process of finding and fixing bugs (errors or mistakes) in a computer program.
Debugging Computer Networks Sep. 26, 2007 Seunghwan Hong.
S OME USEFUL D EBUG C OMMANDS FOR C LEAR -S PEED S OFTWARE D EVELOPMENT K IT -- COMMANDS FROM CHAP.7 By: Pallav Laskar.
 2003 Prentice Hall, Inc. All rights reserved. 1 IS 0020 Program Design and Software Tools Preprocessor Midterm Review Lecture 7 Feb 17, 2004.
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!)
Minimal standard C program int main(void) { return 0 ; }
THE PREPROCESSOR
17/02/2016S. Ponce / EP-LBC1 Debugging Under Linux Sebastien Ponce Friday, 8 March 2002.
1 Object-Oriented Programming -- Using C++ Andres, Wen-Yuan Liao Department of Computer Science and Engineering De Lin Institute of Technology
Adv. UNIX:pre/111 Advanced UNIX v Objectives of these slides: –look at the features of the C preprocessor Special Topics in Comp. Eng.
A.Abhari CPS1251 Topic 2: C Overview C Language Elements Variable Declaration and Data Types Statement Execution C Program Layout Formatting Output Interactive.
Debugging: Tips and Tools Also, Aloha Recitation Wednesday, February 7th, 2007.
CMSC 104, Version 8/061L14AssignmentOps.ppt Assignment Operators Topics Increment and Decrement Operators Assignment Operators Debugging Tips Reading Section.
CS252: Systems Programming Ninghui Li Based on Slides by Gustavo Rodriguez-Rivera Topic 2: Program Structure and Using GDB.
CPT: Debug/ Computer Programming Techniques Semester 1, 1998 Objective of these slides: –to talk about the various approaches to testing.
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.
HP-SEE Debugging with GDB Vladimir Slavnic Research Assistant SCL, Institute of Physics Belgrade The HP-SEE initiative.
Institute of Radio Physics and Electronics ILug-Cal Introduction to GDB Institute of Radio Physics and Electronics and Indian GNU/Linux Users Group Kolkata.
Winter 2009 Tutorial #6 Arrays Part 2, Structures, Debugger
CSE 374 Programming Concepts & Tools
CS1101X Programming Methodology
Testing and Debugging.
gdb gdb is the GNU debugger on our CS machines.
Common C Programming Errors, GDB Debugging
Programming in C Miscellaneous Topics.
When your program crashes
Chapter 15 Debugging.
Programming in C Miscellaneous Topics.
Your questions from last session
Homework Applied for cs240? (If not, keep at it!) 8/10 Done with HW1?
C Programming Getting started Variables Basic C operators Conditionals
Homework Reading Programming Assignments Finish K&R Chapter 1
Homework Continue with K&R Chapter 5 Skipping sections for now
Computer Programming Techniques Semester 1, 1998
Chapter 15 Debugging.
Debugging.
Makefiles, GDB, Valgrind
Chapter 15 Debugging.
Presentation transcript:

Adv. UNIX: debug/141 Advanced UNIX v Objectives of these slides: –tools and techniques for debugging C code Special Topics in Comp. Eng. 1 Semester 2, Debugging

Adv. UNIX: debug/142 Overview 1. What is Debugging? 2. Catching Errors at Compile Time 3. Debugging with printf() 's 4. Conditional Compilation 5. assert() 6. gdb 7. Memory Leaks 8. More Information

Adv. UNIX: debug/ What is Debugging? v Debugging is the process of locating and removing errors. v It has been estimated that 85% of debugging time is spent locating errors and only 15% spent fixing them –tools that speed up locating are very useful

Adv. UNIX: debug/144 Common C Coding Mistakes v Array index out of bounds v Unintended side effects –e.g. a = b instead of a == b v Use of uninitialised variables  case fall-through in a switch continued

Adv. UNIX: debug/145 v Pointers (memory leaks)  Reversed logic in conditions e.g. x 5 v Macros v Unterminated comments

Adv. UNIX: debug/ Catching Errors at Compile Time  Use the -Wall option of gcc : $ gcc -Wall -o example example.c v Extra warnings include: –not using a locally defined variable –not declaring a function

Adv. UNIX: debug/147 Example: useWall.c v v int main() { int a, b; int x1, x2; if (a = b) printf("%d\n", x1); return 0; }

Adv. UNIX: debug/148 v v $ gcc -o useWall useWall.c $ useWall $ gcc -Wall -o useWall useWall.c useWall.c: In function `main': useWall.c:9: warning: suggest parentheses around assignment used as truth value useWall.c:10: warning: implicit declaration of function `printf' useWall.c:7: warning: unused variable `x2' $ useWall Three warnings, along with line numbers.

Adv. UNIX: debug/149 Finding Line 10 in vi  Use G : –e.g. 10G or:  Switch on line numbering in vi : –:set nu –:set nonu /* to switch it off */

Adv. UNIX: debug/ Debugging with printf() s v Good places to add them in your code: –at the start of a function u to print input parameters –at the return point of a function u to print output parameters and the return value –at the start of a loop u print the loop counter continued

Adv. UNIX: debug/1411   printf() s must identify where they are in the code: – –e.g. print the function name, line number, as well as data values – –use __LINE__, and others   printf() s should be conditional – –see the next section

Adv. UNIX: debug/1412 Example: dprintf.c v v #include int main() { int x = 5; printf("Compiled: %s %s\n", __DATE__, __TIME__); printf("%s/main.%d: x=%d\n", __FILE__, __LINE__, x); printf("hello world, x=%d\n", x); return 0; }

Adv. UNIX: debug/1413 v v $ gcc -Wall -o dprintf dprintf.c $ dprintf Compiled: Dec :27:44 dprintf.c/main.11: x=5 hello world, x=5 the debugging printf is located by program/function. line number

Adv. UNIX: debug/ Conditional Compilation  Debugging printf() s can be 'switched off' by putting comments around them –but adding comments takes a lot of time v Conditional compilation: selectively compile portions of the program –conditional compilation can be used to select which printf() s to include in the compilation

Adv. UNIX: debug/1415 Example: cinfo.c v v #include int main() { int x = 5; #ifdef DEBUG printf("Compiled: %s %s\n", __DATE__, __TIME__); printf("%s/main.%d: x=%d\n", __FILE__, __LINE__, x); #endif printf("hello world, x=%d\n", x); return 0; }

Adv. UNIX: debug/1416 v $ gcc -Wall -o cinfo cinfo.c $ cinfo hello world, x=5 $ gcc -Wall -o cinfo cinfo.c -DDEBUG $ cinfo Compiled: Dec :39:14 cinfo.c/main.15: x=5 hello world, x=5 define the DEBUG constant

Adv. UNIX: debug/1417 Harder Debug Switching  Instead of having the -D option on the command line, the constant can be defined inside the program: #define DEBUG v This is more work.

Adv. UNIX: debug/1418 Fancier #if: ifsdebug.c #include int main() { int n1 = 1, n2 = 2, n3 = 3; #if TESTFLAG == 1 printf("main: n1=%d\n", n1); #elif TESTFLAG == 2 printf("main: n2=%d\n", n2); #else printf("main: n3=%d\n", n3); #endif printf("n1=%d, n2=%d, n3=%d\n", n1, n2, n3); return 0; }

Adv. UNIX: debug/1419 v v $ gcc -Wall -o ifsdebug ifsdebug.c -DTESTFLAG=1 $ ifsdebug main: n1=1 n1=1, n2=2, n3=3 $ gcc -Wall -o ifsdebug ifsdebug.c -DTESTFLAG=2 $ ifsdebug main: n2=2 n1=1, n2=2, n3=3 $ gcc -Wall -o ifsdebug ifsdebug.c $ ifsdebug main: n3=3 n1=1, n2=2, n3=3 No -D option means that TESTFLAG is undefined.

Adv. UNIX: debug/ assert() v For testing assertions about the program.  assert() calls can contain any C expression: assert(x==y); assert(ptr != NULL); v If the evaluation is 0 (false) at runtime, an error message is produced, and execution is aborted.

Adv. UNIX: debug/1421 Example: assertTest.c v v #include #include #include double my_sqrt(double x); int main() { printf("sqrt +2 = %g\n", my_sqrt(2.0)); printf("sqrt -2 = %g\n", my_sqrt(-2.0)); return 0; } double my_sqrt(double x) { assert(x >= 0.0); return sqrt(x); }

Adv. UNIX: debug/1422 v v $ gcc -Wall -o assertTest assertTest.c -lm $ assertTest sqrt +2 = assertTest: assertTest.c:20: my_sqrt: Assertion `x >= 0.0' failed. Aborted $ gcc -Wall -o assertTest assertTest.c -lm -DNDEBUG $ assertTest sqrt +2 = sqrt -2 = nan $ assert() switched off "not a number"

Adv. UNIX: debug/ gdb  gdb is the interactive source-level debugger from the GNU Project –the debugger allows the programmer to see bugs in the source code as the program executes  Information on gdb : –$ man gdb –$ gdb -help –$ info gdb –type help when running gdb

Adv. UNIX: debug/ Main Features v Source line stepping v Printing/monitoring variables v Source-level breakpoints v Analysing core dumps v Graphical interfaces exist (using X) –xxgdb

Adv. UNIX: debug/ How to use gdb 1) Compile with the -g option of gcc : $ gcc -g -o examp examp.c 2) Execute the object code within gdb : $ gdb examp

Adv. UNIX: debug/ gdb and Crashing Code v v include void foo(int *px); void bar(int *px); int main() { int *px; px = (int *) 1000; /* px is address 1000 */ foo(px); return 0; } void foo(int *px) { bar(px); } void bar(int *px) { *px = 3; } /* assign 3 into address 1000 */ crash.c

Adv. UNIX: debug/1427 v v $ gcc -Wall -o crash crash.c $ crash Segmentation fault $ gcc -Wall -g -o crash crash.c $ gdb crash GNU gdb. Copyright (gdb) run Starting program: crash Program received signal SIGSEGV, Segmentation fault. 0x80483f2 in bar (px=0x3e8) at crash.c:27 27 *px = 3; (gdb) where #0 0x80483f2 in bar (px=0x3e8) at crash.c:27 #1 0x80483e6 in foo (px=0x3e8) at crash.c:22 #2 0x80483c9 in main () at crash.c:16 (gdb) quit The program is running. Exit anyway? (y or n) y $ crash crashes at line 27 in bar()

Adv. UNIX: debug/ gdb and Non-terminating Code 1. Start the code: run 2. Wait; interrupt execution: ctrl-c 3. Find location: where –list –list –print –print 4. Step through the code: step

Adv. UNIX: debug/1429 Example: nonterm.c v v include int main() { int num = 1; while (num > 0) if (num*num > 10000) { printf("Largest n is %d\n", num-1); num++; } return 0; }

Adv. UNIX: debug/1430 v v $ gcc -Wall -g -o nonterm nonterm.c $ gdb nonterm GNU gdb Copyright... (gdb) run Starting program: nonterm Program received signal SIGINT, Interrupt. 0x in main () at nonterm.c:12 12 if (num*num > 10000) { (gdb) where #0 0x in main () at nonterm.c:12 : I typed ctrl-C

Adv. UNIX: debug/1431 (gdb) list 7 int main() 8 { 9 int num = 1; while (num > 0) 12 if (num*num > 10000) { 13 printf("Largest n is %d\n", num-1); 14 num++; 15 } 16 return 0; (gdb) print num $1 = 1 (gdb) cont Continuing. Program received signal SIGINT, Interrupt. main () at nonterm.c:15 15 } : I typed ctrl-C again

Adv. UNIX: debug/1432 v v (gdb) print num $2 = 1 (gdb) step 12 if (num*num > 10000) { (gdb) step 15 } (gdb) step 12 if (num*num > 10000) { (gdb) step 15 } (gdb) quit The program is running. Exit anyway? (y or n) y $

Adv. UNIX: debug/1433 Getting indents Right v v $ indent -kr nonterm.c -o nonterm2.c $ cat nonterm2.c #include int main() { int num = 1; while (num > 0) if (num * num > 10000) { printf("Largest n is %d\n", num - 1); num++; } return 0; }

Adv. UNIX: debug/ gdb and Wrong Answers 1)Think about the error before using gdb. 2)Put breakpoints into the code. 3)Run the code. 4)At each breakpoint, step through the code. 5)Print variables and list code often: 6)If the code looks okay, continue execution. 7)Delete breakpoints that are no longer needed.

Adv. UNIX: debug/1435 Example: lowercase.c v v /* convert input to lowercase */ #include #include #define SIZE 1024 void lower(char lin[]); int main() { char line[SIZE]; while (fgets(line, 1024, stdin) != NULL) { lower(line); fputs(line, stdout); } return 0; } continued

Adv. UNIX: debug/1436 void lower(char lin[]) /* convert any uppercase letters to lowercase */ { int count = 0; while (lin[count] != '\0') { if (isupper(lin[count])) /* lin[count] = tolower(lin[count]); */ lin[count] += 34; count++; } }

Adv. UNIX: debug/1437 The Debugging Process v v $ gcc -Wall -g -o lowercase lowercase.c $ lowercase abcde abcde AAAAA ccccc BBBAAAA dddcccc $ gdb lowercase GNU gdb... (gdb) break lower Breakpoint 1 at 0x80484ee: file lowercase.c, line 28. : something is wrong

Adv. UNIX: debug/1438 (gdb) run Starting program: lowercase AAAAA Breakpoint 1, lower (lin=0xbffff8fc "AAAAA\n") at lowercase.c:28 28 int count = 0; (gdb) finish Run till exit from #0 lower (lin=0xbffff8fc "AAAAA\n") at lowercase.c:28 0x80484c4 in main () at lowercase.c:17 17 lower(line); (gdb) print $1 = "ccccc\n\000\000\000" : typed in by me

Adv. UNIX: debug/1439 (gdb) info break Num Type Disp Enb Address What 1 breakpoint keep y 0x080484ee in lower at lowercase.c:28 breakpoint already hit 1 time (gdb) delete 1 (gdb) list int count = 0; while (lin[count] != '\0') { 31 if (isupper(lin[count])) 32/* lin[count] = tolower(lin[count]); */ 33 lin[count] += 34; 34 count++; 35 } 36} 37 :

Adv. UNIX: debug/1440 (gdb) break 33 Breakpoint 2 at 0x : file lowercase.c, line 33. (gdb) cont Continuing. ccccc BBBBAAAA Breakpoint 2, lower (lin=0xbffff8fc "BBBBAAAA\n") at lowercase.c:33 33 lin[count] += 34; (gdb) step 34 count++; (gdb) print $2 = "dBBBAAAA\n" (gdb) quit The program is running. Exit anyway? (y or n) y $ typed in by me

Adv. UNIX: debug/ Memory Leaks  Dynamic data created with malloc() is not checked when it is used –it is easy for a programmer to assign data outside the malloc'ed area –the error will probably not cause a crash until much later when the altered memory is accessed by another part of the program continued

Adv. UNIX: debug/1442 v There are a number of tools which monitor the usage of malloc'ed space, and cause an error if they are used incorrectly –the ElectricFence library ( efence ) –the checkergcc compiler

Adv. UNIX: debug/1443 Example: efTest.c v v #include #include int main() { char *ptr = (char *)malloc(1024); ptr[0] = 0; /* now write beyond the block */ ptr[1024] = 0; printf("Everything is wondeful (I don't think)\n"); exit(0); }

Adv. UNIX: debug/1444 Execution v v $ gcc -Wall -o efTest efTest.c $ efTest Everything is wondeful (I don't think) $ gcc -Wall -o efTest efTest.c -lefence $ efTest Electric Fence Copyright (C) Bruce Perens. Segmentation fault $ continued

Adv. UNIX: debug/1445 $ gcc -Wall -g -o efTest efTest.c -lefence $ gdb efTest GNU gdb... (gdb) run Starting program: efTest Electric Fence Copyright (C) Bruce Perens. Program received signal SIGSEGV, Segmentation fault. 0x80485c9 in main () at efTest.c:17 17 ptr[1024] = 0; (gdb) quit The program is running. Exit anyway? (y or n) y $

Adv. UNIX: debug/ More Information v Beginning Linux Programming Neil Matthew and Rick Stones Wrox Press, 1996 Chapter 9: Debugging