2 debugging-c

228 views
178 views

Published on

fghf

Published in: Technology
0 Comments
0 Likes
Statistics
Notes
  • Be the first to comment

  • Be the first to like this

No Downloads
Views
Total views
228
On SlideShare
0
From Embeds
0
Number of Embeds
2
Actions
Shares
0
Downloads
4
Comments
0
Likes
0
Embeds 0
No embeds

No notes for slide

2 debugging-c

  1. 1. Debugging C Programs Mark HandleyWhat is debugging? Debugging is not getting the compiler to compile your code without syntax errors or linking errors.  Although this can sometimes take some time when a language is unfamiliar. Debugging is what you do when your code compiles, but it doesn’t run the way you expected.  “Why doesn’t it work? What do I do now?” 1
  2. 2. Grace Hopper, 1945Debugging Hints To solve a problem, you must understand it. Make life easier for yourself:  Indent your code properly.  Use meaningful variable names.  Print debugging to stderr or stdout, but not both, or your debugging output may be reordered.  Develop incrementally. Test as you go. 2
  3. 3. Get the Compiler to Help! The C compiler isn’t as pedantic as a Java compiler, but it can still help you out. Use the compiler flags. With gcc:  -g includes debugging systems  -Wall turns on (almost) all compiler warnings.  Eg: gcc -g -Wall -o foo foo.c Use the manual. On Unix the man pages are an excellent reference for all standard library functions:  man fgetsFGETS(3) FreeBSD Library Functions Manual FGETS(3)NAME fgets, gets -- get a line from a streamLIBRARY Standard C Library (libc, -lc)SYNOPSIS #include <stdio.h> char * fgets(char *str, int size, FILE *stream); char * gets(char *str);DESCRIPTION The fgets() function reads at most one less than the number of characters specified by size from the given stream and stores them in the string str. Reading stops when a newline character is found, at end-of-file or error. The newline, if any, is retained. If any characters are read and there is no error, a `0 character is appended to end the string. 3
  4. 4. Debugging Hints When it doesn’t work, pause, read the output very carefully, read your code, and think first.  It is way too easy to start hacking, without reviewing the evidence that’s in front of your nose. If there is not enough evidence to find and understand a problem, you need to gather more evidence.  This is the key to debugging.Gathering Evidence Two ways to fail: 1. Program did something different from what you expected. 2. Program crashed. In C, likely symptoms of a crash: Segmentation fault: core dumped. Bus error: core dumped. Floating point exception: core dumped. We’ll deal with crashes a little later. 4
  5. 5. Gathering Evidence Program did something different from what you expected.  Task 1: figure out what the program did do.  Task 2: figure out how to make it do what you wanted it to do. Don’t jump in to task 2 before doing task 1. You’ll probably break something else, and still not fix the bug.  And there may be similar bugs elsewhere in your code because you made the same error more than once. Don’t jump into the debugger first - it stops you reading your code. A debugger is only one debugging tool.  Occasionally code behaves differently in a debugger.Gathering Evidence Did the program take the path through your code that you expected? How do you know?  Annotate the expected code path.  printf(“here 7n”);  printf(“entering factorial()n”);  printf(“leaving factorial()n”);  It’svery common for your program to take a different path.  Often when you see this, the bug will be obvious. 5
  6. 6. Gathering EvidencePrint the values of key variables. What are you looking for? Did you initialise them?  C won’t usually notice if you didn’t. Were type conversions done correctly? Did you pass the parameters in the wrong order?  Print out the parameters as they were received in the function. Did you pass the right number of parameters?  C won’t always notice. Did some memory get overwritten?  A variable spontaneously changes value!Common C Errors Missing break in a switch statement Using = instead of ==  if (a = 0) { ..... } Spurious semicolon: while (x < 10); x++; Missing parameters: printf(“The value of a is %dn”); Wrong parameter type in printf, scanf, etc: double num; printf(“The value of n is %dn”, num); 6
  7. 7. Common C Errors Array indexing:  int a[10]; has indices from 0 to 9 Comparing Strings: char s1 = “test” char s1 = “test” if (s1 == s2) printf(“Equaln”);  You must use strcmp() or strncmp() to compare strings.Common C Errors Integer division: double half = 1/2;  This sets half to 0 not 0.5!  1 and 2 are integer constants.  At least one needs to be floating point: double half = 1.0/2;  Or cast one to floating point: int a = 1, b = 2; double half = ((double)1)/2. 7
  8. 8. Common C ErrorsMissing headers or prototypes:double x = sqrt(2);  sqrt is a standard function defined in the maths library.  It won’t work properly if you forget to include math.h which defines the function prototype: double sqrt(double)  C assumes a function returns an int if it doesn’t know better.  Also link with -lm: gcc -o foo -lm foo.cCommon C ErrorsSpurious pointers:  char *buffer;  fgets(buffer, 80, stdin);With pointers, always ask yourself :  “Which memory is this pointer pointing to?”.  If it’s not pointing anywhere, then assign it the value NULL  If your code allows a pointer to be NULL, you must check for this before following the pointer. 8
  9. 9. Crashes[eve:~] mjh% gcc -g -o foo foo.c[eve:~] mjh% ./fooEnter an integer: 10Enter an integer: 20Enter an integer: Finished Value: 20 Value: 10 Bus error (core dumped) [eve] mjh%What do you do now?Core FilesSegmentation fault: core dumped. The program tried to access memory that did not belong to it. The error was detected by the OS.Bus error: core dumped. The program tried to access memory that did not belong to it. The error was detected by the CPU.Floating point exception: core dumped. The CPU’s floating point unit trapped an error.In all these, the OS was kind enough to save your program’s memory image at the time of the crash in a core file. 9
  10. 10. Crashes[eve:~] mjh% gcc -g -o foo foo.c[eve:~] mjh% ./fooEnter an integer: 10Enter an integer: 20Enter an integer: Finished Value: 20 Value: 10 Bus error (core dumped)[eve] mjh% gdb foo foo.core GNU gdb 5.3-20030128 (Apple version gdb-309) ... Core was generated by `./foo. #0 0x00001d20 in main () at foo.c:44 44 printf("Value: %dn", p->value);(gdb) print p $1 = (struct element *) 0x0 10
  11. 11. The culprit/* print out the numbers we stored */ p = head; for (i=0; i<10; i++) { printf("Value: %dn", p->value); p = p->next; }Breakpoints(gdb) break foo.c:44 Breakpoint 1 at 0x1d14: file foo.c, line 44.(gdb) runEnter an integer: 10Enter an integer: Finished Breakpoint 1, main () at foo.c:44 44 printf("Value: %dn", p->value);(gdb) print p $2 = (struct element *) 0x100140(gdb) cont Continuing. Value: 10 Breakpoint 1, main () at foo.c:44 44 printf("Value: %dn", p->value);(gdb) print p $3 = (struct element *) 0x0 11
  12. 12. Stack tracesstruct element { int value; struct element* next;};void print_element(struct element *p) { printf("Value: %dn", p->value);}void print_list(struct element *p) { print_element(p); print_list(p->next);}main() { struct element *head = NULL; /* read in some numbers */... print_list(head);}Stack traces[eve:~] mjh% gdb foo foo.core GNU gdb 5.3-20030128 (Apple version gdb-309) (Thu Dec 4 15:41:30 GMT 2003) ... Core was generated by `./foo. #0 0x00001c04 in print_element (p=0x0) at foo.c:11 11 printf("Value: %dn", p->value);(gdb) bt #0 0x00001c04 in print_element (p=0x0) at foo.c:11 #1 0x00001c40 in print_list (p=0x0) at foo.c:15 #2 0x00001c4c in print_list (p=0x300140) at foo.c:16 #3 0x00001c4c in print_list (p=0x300150) at foo.c:16 #4 0x00001d20 in main () at foo.c:52(gdb) up 2 #2 0x00001c4c in print_list (p=0x300140) at foo.c:16 16 print_list(p->next);(gdb) print p->next $1 = (struct element *) 0x0 12
  13. 13. Conclusions Lots of ways to shoot yourself in the foot. Good style helps prevent dumb errors because your code is more readable. Debugging is an art, acquired by practice. If you’re really stuck, take a break.  Debugging is hard if you’re tired.  Your subconscious often needs space to debug your code by itself. 13

×