SlideShare uma empresa Scribd logo
1 de 13
Baixar para ler offline
Debugging C Programs


                                          Mark Handley




What 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
Grace Hopper, 1945




Debugging 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
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    fgets




FGETS(3)                  FreeBSD Library Functions Manual           FGETS(3)

NAME
       fgets, gets -- get a line from a stream

LIBRARY
     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
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
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
Gathering Evidence
Print 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
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
Common C Errors
Missing 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.c




Common C Errors
Spurious 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
Crashes
[eve:~] mjh% gcc -g -o foo foo.c
[eve:~] mjh% ./foo
Enter an integer: 10
Enter an integer: 20
Enter an integer: Finished
 Value: 20
 Value: 10
 Bus error (core dumped)
 [eve] mjh%


What do you do now?




Core Files
Segmentation 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
Crashes
[eve:~] mjh% gcc -g -o foo foo.c
[eve:~] mjh% ./foo
Enter an integer: 10
Enter an integer: 20
Enter 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
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) run
Enter an integer: 10
Enter 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
Stack traces
struct 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
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

Mais conteúdo relacionado

Mais procurados

Handling Exceptions In C &amp; C++ [Part B] Ver 2
Handling Exceptions In C &amp; C++ [Part B] Ver 2Handling Exceptions In C &amp; C++ [Part B] Ver 2
Handling Exceptions In C &amp; C++ [Part B] Ver 2ppd1961
 
Valgrind overview: runtime memory checker and a bit more aka использование #v...
Valgrind overview: runtime memory checker and a bit more aka использование #v...Valgrind overview: runtime memory checker and a bit more aka использование #v...
Valgrind overview: runtime memory checker and a bit more aka использование #v...Minsk Linux User Group
 
A few words about OpenSSL
A few words about OpenSSLA few words about OpenSSL
A few words about OpenSSLPVS-Studio
 
Tesseract. Recognizing Errors in Recognition Software
Tesseract. Recognizing Errors in Recognition SoftwareTesseract. Recognizing Errors in Recognition Software
Tesseract. Recognizing Errors in Recognition SoftwareAndrey Karpov
 
Hands-on Introduction to the C Programming Language
Hands-on Introduction to the C Programming LanguageHands-on Introduction to the C Programming Language
Hands-on Introduction to the C Programming LanguageVincenzo De Florio
 
Common mistakes in C programming
Common mistakes in C programmingCommon mistakes in C programming
Common mistakes in C programmingLarion
 
Checking Intel IPP Samples for Windows - Continuation
Checking Intel IPP Samples for Windows - ContinuationChecking Intel IPP Samples for Windows - Continuation
Checking Intel IPP Samples for Windows - ContinuationPVS-Studio
 
Valgrind debugger Tutorial
Valgrind debugger TutorialValgrind debugger Tutorial
Valgrind debugger TutorialAnurag Tomar
 

Mais procurados (17)

Handling Exceptions In C &amp; C++ [Part B] Ver 2
Handling Exceptions In C &amp; C++ [Part B] Ver 2Handling Exceptions In C &amp; C++ [Part B] Ver 2
Handling Exceptions In C &amp; C++ [Part B] Ver 2
 
PHP 5.3
PHP 5.3PHP 5.3
PHP 5.3
 
88 c-programs
88 c-programs88 c-programs
88 c-programs
 
Valgrind overview: runtime memory checker and a bit more aka использование #v...
Valgrind overview: runtime memory checker and a bit more aka использование #v...Valgrind overview: runtime memory checker and a bit more aka использование #v...
Valgrind overview: runtime memory checker and a bit more aka использование #v...
 
C programming language
C programming languageC programming language
C programming language
 
Deep C
Deep CDeep C
Deep C
 
C++ Core Guidelines
C++ Core GuidelinesC++ Core Guidelines
C++ Core Guidelines
 
A few words about OpenSSL
A few words about OpenSSLA few words about OpenSSL
A few words about OpenSSL
 
Tesseract. Recognizing Errors in Recognition Software
Tesseract. Recognizing Errors in Recognition SoftwareTesseract. Recognizing Errors in Recognition Software
Tesseract. Recognizing Errors in Recognition Software
 
C tutorial
C tutorialC tutorial
C tutorial
 
Hands-on Introduction to the C Programming Language
Hands-on Introduction to the C Programming LanguageHands-on Introduction to the C Programming Language
Hands-on Introduction to the C Programming Language
 
Common mistakes in C programming
Common mistakes in C programmingCommon mistakes in C programming
Common mistakes in C programming
 
Checking Intel IPP Samples for Windows - Continuation
Checking Intel IPP Samples for Windows - ContinuationChecking Intel IPP Samples for Windows - Continuation
Checking Intel IPP Samples for Windows - Continuation
 
Wtf per lineofcode
Wtf per lineofcodeWtf per lineofcode
Wtf per lineofcode
 
2 data and c
2 data and c2 data and c
2 data and c
 
Valgrind debugger Tutorial
Valgrind debugger TutorialValgrind debugger Tutorial
Valgrind debugger Tutorial
 
C operators
C operatorsC operators
C operators
 

Semelhante a 2 debugging-c

Semelhante a 2 debugging-c (20)

Csdfsadf
CsdfsadfCsdfsadf
Csdfsadf
 
C
CC
C
 
What is turbo c and how it works
What is turbo c and how it worksWhat is turbo c and how it works
What is turbo c and how it works
 
Deep C Programming
Deep C ProgrammingDeep C Programming
Deep C Programming
 
Unit 1 c - all topics
Unit 1   c - all topicsUnit 1   c - all topics
Unit 1 c - all topics
 
The basics of c programming
The basics of c programmingThe basics of c programming
The basics of c programming
 
C tutorial
C tutorialC tutorial
C tutorial
 
C tutorial
C tutorialC tutorial
C tutorial
 
Introduction to c programming
Introduction to c programmingIntroduction to c programming
Introduction to c programming
 
88 c programs 15184
88 c programs 1518488 c programs 15184
88 c programs 15184
 
88 c-programs
88 c-programs88 c-programs
88 c-programs
 
COMP 2103X1 Assignment 2Due Thursday, January 26 by 700 PM.docx
COMP 2103X1 Assignment 2Due Thursday, January 26 by 700 PM.docxCOMP 2103X1 Assignment 2Due Thursday, January 26 by 700 PM.docx
COMP 2103X1 Assignment 2Due Thursday, January 26 by 700 PM.docx
 
C programming day#1
C programming day#1C programming day#1
C programming day#1
 
C++ lecture 01
C++   lecture 01C++   lecture 01
C++ lecture 01
 
C Programming Tutorial - www.infomtec.com
C Programming Tutorial - www.infomtec.comC Programming Tutorial - www.infomtec.com
C Programming Tutorial - www.infomtec.com
 
Fundamental of C Programming Language and Basic Input/Output Function
  Fundamental of C Programming Language and Basic Input/Output Function  Fundamental of C Programming Language and Basic Input/Output Function
Fundamental of C Programming Language and Basic Input/Output Function
 
Structures-2
Structures-2Structures-2
Structures-2
 
C tutorial
C tutorialC tutorial
C tutorial
 
Design problem
Design problemDesign problem
Design problem
 
Boo Manifesto
Boo ManifestoBoo Manifesto
Boo Manifesto
 

Último

SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024Lorenzo Miniero
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubKalema Edgar
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Scott Keck-Warren
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek SchlawackFwdays
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):comworks
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfAddepto
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Enterprise Knowledge
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfAlex Barbosa Coqueiro
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteDianaGray10
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Mattias Andersson
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxhariprasad279825
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsRizwan Syed
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsPixlogix Infotech
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebUiPathCommunity
 
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionDilum Bandara
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024Lonnie McRorey
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenHervé Boutemy
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024Stephanie Beckett
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...Fwdays
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxNavinnSomaal
 

Último (20)

SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding Club
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdf
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdf
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test Suite
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptx
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL Certs
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and Cons
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio Web
 
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An Introduction
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache Maven
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptx
 

2 debugging-c

  • 1. Debugging C Programs Mark Handley What 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. Grace Hopper, 1945 Debugging 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. 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 fgets FGETS(3) FreeBSD Library Functions Manual FGETS(3) NAME fgets, gets -- get a line from a stream LIBRARY 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. 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. 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. Gathering Evidence Print 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. 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. Common C Errors Missing 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.c Common C Errors Spurious 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. Crashes [eve:~] mjh% gcc -g -o foo foo.c [eve:~] mjh% ./foo Enter an integer: 10 Enter an integer: 20 Enter an integer: Finished Value: 20 Value: 10 Bus error (core dumped) [eve] mjh% What do you do now? Core Files Segmentation 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. Crashes [eve:~] mjh% gcc -g -o foo foo.c [eve:~] mjh% ./foo Enter an integer: 10 Enter an integer: 20 Enter 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. 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) run Enter an integer: 10 Enter 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. Stack traces struct 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. 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