SlideShare ist ein Scribd-Unternehmen logo
1 von 13
Downloaden Sie, um offline zu lesen
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

Weitere ähnliche Inhalte

Was ist angesagt?

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
 

Was ist angesagt? (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
 

Ähnlich wie 2 debugging-c

Ähnlich wie 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
 

Kürzlich hochgeladen

Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...Alkin Tezuysal
 
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...Wes McKinney
 
Bridging Between CAD & GIS: 6 Ways to Automate Your Data Integration
Bridging Between CAD & GIS:  6 Ways to Automate Your Data IntegrationBridging Between CAD & GIS:  6 Ways to Automate Your Data Integration
Bridging Between CAD & GIS: 6 Ways to Automate Your Data Integrationmarketing932765
 
React Native vs Ionic - The Best Mobile App Framework
React Native vs Ionic - The Best Mobile App FrameworkReact Native vs Ionic - The Best Mobile App Framework
React Native vs Ionic - The Best Mobile App FrameworkPixlogix Infotech
 
Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...Farhan Tariq
 
Design pattern talk by Kaya Weers - 2024 (v2)
Design pattern talk by Kaya Weers - 2024 (v2)Design pattern talk by Kaya Weers - 2024 (v2)
Design pattern talk by Kaya Weers - 2024 (v2)Kaya Weers
 
Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024Hiroshi SHIBATA
 
QCon London: Mastering long-running processes in modern architectures
QCon London: Mastering long-running processes in modern architecturesQCon London: Mastering long-running processes in modern architectures
QCon London: Mastering long-running processes in modern architecturesBernd Ruecker
 
All These Sophisticated Attacks, Can We Really Detect Them - PDF
All These Sophisticated Attacks, Can We Really Detect Them - PDFAll These Sophisticated Attacks, Can We Really Detect Them - PDF
All These Sophisticated Attacks, Can We Really Detect Them - PDFMichael Gough
 
Microsoft 365 Copilot: How to boost your productivity with AI – Part one: Ado...
Microsoft 365 Copilot: How to boost your productivity with AI – Part one: Ado...Microsoft 365 Copilot: How to boost your productivity with AI – Part one: Ado...
Microsoft 365 Copilot: How to boost your productivity with AI – Part one: Ado...Nikki Chapple
 
Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...
Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...
Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...panagenda
 
Top 10 Hubspot Development Companies in 2024
Top 10 Hubspot Development Companies in 2024Top 10 Hubspot Development Companies in 2024
Top 10 Hubspot Development Companies in 2024TopCSSGallery
 
React JS; all concepts. Contains React Features, JSX, functional & Class comp...
React JS; all concepts. Contains React Features, JSX, functional & Class comp...React JS; all concepts. Contains React Features, JSX, functional & Class comp...
React JS; all concepts. Contains React Features, JSX, functional & Class comp...Karmanjay Verma
 
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyesHow to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyesThousandEyes
 
UiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPathCommunity
 
Landscape Catalogue 2024 Australia-1.pdf
Landscape Catalogue 2024 Australia-1.pdfLandscape Catalogue 2024 Australia-1.pdf
Landscape Catalogue 2024 Australia-1.pdfAarwolf Industries LLC
 
A Glance At The Java Performance Toolbox
A Glance At The Java Performance ToolboxA Glance At The Java Performance Toolbox
A Glance At The Java Performance ToolboxAna-Maria Mihalceanu
 
4. Cobus Valentine- Cybersecurity Threats and Solutions for the Public Sector
4. Cobus Valentine- Cybersecurity Threats and Solutions for the Public Sector4. Cobus Valentine- Cybersecurity Threats and Solutions for the Public Sector
4. Cobus Valentine- Cybersecurity Threats and Solutions for the Public Sectoritnewsafrica
 
Time Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsTime Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsNathaniel Shimoni
 
So einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdfSo einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdfpanagenda
 

Kürzlich hochgeladen (20)

Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
 
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
 
Bridging Between CAD & GIS: 6 Ways to Automate Your Data Integration
Bridging Between CAD & GIS:  6 Ways to Automate Your Data IntegrationBridging Between CAD & GIS:  6 Ways to Automate Your Data Integration
Bridging Between CAD & GIS: 6 Ways to Automate Your Data Integration
 
React Native vs Ionic - The Best Mobile App Framework
React Native vs Ionic - The Best Mobile App FrameworkReact Native vs Ionic - The Best Mobile App Framework
React Native vs Ionic - The Best Mobile App Framework
 
Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...
 
Design pattern talk by Kaya Weers - 2024 (v2)
Design pattern talk by Kaya Weers - 2024 (v2)Design pattern talk by Kaya Weers - 2024 (v2)
Design pattern talk by Kaya Weers - 2024 (v2)
 
Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024
 
QCon London: Mastering long-running processes in modern architectures
QCon London: Mastering long-running processes in modern architecturesQCon London: Mastering long-running processes in modern architectures
QCon London: Mastering long-running processes in modern architectures
 
All These Sophisticated Attacks, Can We Really Detect Them - PDF
All These Sophisticated Attacks, Can We Really Detect Them - PDFAll These Sophisticated Attacks, Can We Really Detect Them - PDF
All These Sophisticated Attacks, Can We Really Detect Them - PDF
 
Microsoft 365 Copilot: How to boost your productivity with AI – Part one: Ado...
Microsoft 365 Copilot: How to boost your productivity with AI – Part one: Ado...Microsoft 365 Copilot: How to boost your productivity with AI – Part one: Ado...
Microsoft 365 Copilot: How to boost your productivity with AI – Part one: Ado...
 
Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...
Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...
Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...
 
Top 10 Hubspot Development Companies in 2024
Top 10 Hubspot Development Companies in 2024Top 10 Hubspot Development Companies in 2024
Top 10 Hubspot Development Companies in 2024
 
React JS; all concepts. Contains React Features, JSX, functional & Class comp...
React JS; all concepts. Contains React Features, JSX, functional & Class comp...React JS; all concepts. Contains React Features, JSX, functional & Class comp...
React JS; all concepts. Contains React Features, JSX, functional & Class comp...
 
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyesHow to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
 
UiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to Hero
 
Landscape Catalogue 2024 Australia-1.pdf
Landscape Catalogue 2024 Australia-1.pdfLandscape Catalogue 2024 Australia-1.pdf
Landscape Catalogue 2024 Australia-1.pdf
 
A Glance At The Java Performance Toolbox
A Glance At The Java Performance ToolboxA Glance At The Java Performance Toolbox
A Glance At The Java Performance Toolbox
 
4. Cobus Valentine- Cybersecurity Threats and Solutions for the Public Sector
4. Cobus Valentine- Cybersecurity Threats and Solutions for the Public Sector4. Cobus Valentine- Cybersecurity Threats and Solutions for the Public Sector
4. Cobus Valentine- Cybersecurity Threats and Solutions for the Public Sector
 
Time Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsTime Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directions
 
So einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdfSo einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdf
 

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