SlideShare a Scribd company logo
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
Ad

More Related Content

What's hot (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
ppd1961
 
PHP 5.3
PHP 5.3PHP 5.3
PHP 5.3
Chris Stone
 
88 c-programs
88 c-programs88 c-programs
88 c-programs
Leandro Schenone
 
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
 
C programming language
C programming languageC programming language
C programming language
Mahmoud Eladawi
 
Deep C
Deep CDeep C
Deep C
Olve Maudal
 
C++ Core Guidelines
C++ Core GuidelinesC++ Core Guidelines
C++ Core Guidelines
Thomas Pollak
 
A few words about OpenSSL
A few words about OpenSSLA few words about OpenSSL
A few words about OpenSSL
PVS-Studio
 
Tesseract. Recognizing Errors in Recognition Software
Tesseract. Recognizing Errors in Recognition SoftwareTesseract. Recognizing Errors in Recognition Software
Tesseract. Recognizing Errors in Recognition Software
Andrey Karpov
 
C tutorial
C tutorialC tutorial
C tutorial
Khan Rahimeen
 
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
Vincenzo De Florio
 
Common mistakes in C programming
Common mistakes in C programmingCommon mistakes in C programming
Common mistakes in C programming
Larion
 
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
PVS-Studio
 
Wtf per lineofcode
Wtf per lineofcodeWtf per lineofcode
Wtf per lineofcode
David Gómez García
 
2 data and c
2 data and c2 data and c
2 data and c
MomenMostafa
 
Valgrind debugger Tutorial
Valgrind debugger TutorialValgrind debugger Tutorial
Valgrind debugger Tutorial
Anurag Tomar
 
C operators
C operatorsC operators
C operators
srmohan06
 
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
ppd1961
 
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 OpenSSL
PVS-Studio
 
Tesseract. Recognizing Errors in Recognition Software
Tesseract. Recognizing Errors in Recognition SoftwareTesseract. Recognizing Errors in Recognition Software
Tesseract. Recognizing Errors in Recognition Software
Andrey 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 Language
Vincenzo De Florio
 
Common mistakes in C programming
Common mistakes in C programmingCommon mistakes in C programming
Common mistakes in C programming
Larion
 
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
PVS-Studio
 
Valgrind debugger Tutorial
Valgrind debugger TutorialValgrind debugger Tutorial
Valgrind debugger Tutorial
Anurag Tomar
 

Similar to 2 debugging-c (20)

C
CC
C
Anuja Lad
 
Csdfsadf
CsdfsadfCsdfsadf
Csdfsadf
Atul Setu
 
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
Mark John Lado, MIT
 
Deep C Programming
Deep C ProgrammingDeep C Programming
Deep C Programming
Wang Hao Lee
 
Unit 1 c - all topics
Unit 1   c - all topicsUnit 1   c - all topics
Unit 1 c - all topics
veningstonk
 
The basics of c programming
The basics of c programmingThe basics of c programming
The basics of c programming
Muhammed Thanveer M
 
C tutorial
C tutorialC tutorial
C tutorial
Amit Dhiman
 
C tutorial
C tutorialC tutorial
C tutorial
Anuja Lad
 
Introduction to c programming
Introduction to c programmingIntroduction to c programming
Introduction to c programming
Alpana Gupta
 
High performance computing seminar1.pptx
High performance  computing seminar1.pptxHigh performance  computing seminar1.pptx
High performance computing seminar1.pptx
SahithBeats
 
88 c-programs
88 c-programs88 c-programs
88 c-programs
Minh Thắng Trần
 
88 c programs 15184
88 c programs 1518488 c programs 15184
88 c programs 15184
Sumit Saini
 
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
donnajames55
 
C programming day#1
C programming day#1C programming day#1
C programming day#1
Mohamed Fawzy
 
C++ lecture 01
C++   lecture 01C++   lecture 01
C++ lecture 01
HNDE Labuduwa Galle
 
C Programming Tutorial - www.infomtec.com
C Programming Tutorial - www.infomtec.comC Programming Tutorial - www.infomtec.com
C Programming Tutorial - www.infomtec.com
M-TEC Computer Education
 
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
imtiazalijoono
 
Structures-2
Structures-2Structures-2
Structures-2
arshpreetkaur07
 
C tutorial
C tutorialC tutorial
C tutorial
Diwakar_singh1989
 
Design problem
Design problemDesign problem
Design problem
Sanjay Kumar Chakravarti
 
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
Mark John Lado, MIT
 
Deep C Programming
Deep C ProgrammingDeep C Programming
Deep C Programming
Wang Hao Lee
 
Unit 1 c - all topics
Unit 1   c - all topicsUnit 1   c - all topics
Unit 1 c - all topics
veningstonk
 
Introduction to c programming
Introduction to c programmingIntroduction to c programming
Introduction to c programming
Alpana Gupta
 
High performance computing seminar1.pptx
High performance  computing seminar1.pptxHigh performance  computing seminar1.pptx
High performance computing seminar1.pptx
SahithBeats
 
88 c programs 15184
88 c programs 1518488 c programs 15184
88 c programs 15184
Sumit Saini
 
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
donnajames55
 
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
imtiazalijoono
 
Ad

Recently uploaded (20)

Top-AI-Based-Tools-for-Game-Developers (1).pptx
Top-AI-Based-Tools-for-Game-Developers (1).pptxTop-AI-Based-Tools-for-Game-Developers (1).pptx
Top-AI-Based-Tools-for-Game-Developers (1).pptx
BR Softech
 
Could Virtual Threads cast away the usage of Kotlin Coroutines - DevoxxUK2025
Could Virtual Threads cast away the usage of Kotlin Coroutines - DevoxxUK2025Could Virtual Threads cast away the usage of Kotlin Coroutines - DevoxxUK2025
Could Virtual Threads cast away the usage of Kotlin Coroutines - DevoxxUK2025
João Esperancinha
 
Cybersecurity Threat Vectors and Mitigation
Cybersecurity Threat Vectors and MitigationCybersecurity Threat Vectors and Mitigation
Cybersecurity Threat Vectors and Mitigation
VICTOR MAESTRE RAMIREZ
 
IT484 Cyber Forensics_Information Technology
IT484 Cyber Forensics_Information TechnologyIT484 Cyber Forensics_Information Technology
IT484 Cyber Forensics_Information Technology
SHEHABALYAMANI
 
How to Install & Activate ListGrabber - eGrabber
How to Install & Activate ListGrabber - eGrabberHow to Install & Activate ListGrabber - eGrabber
How to Install & Activate ListGrabber - eGrabber
eGrabber
 
Crazy Incentives and How They Kill Security. How Do You Turn the Wheel?
Crazy Incentives and How They Kill Security. How Do You Turn the Wheel?Crazy Incentives and How They Kill Security. How Do You Turn the Wheel?
Crazy Incentives and How They Kill Security. How Do You Turn the Wheel?
Christian Folini
 
Developing System Infrastructure Design Plan.pptx
Developing System Infrastructure Design Plan.pptxDeveloping System Infrastructure Design Plan.pptx
Developing System Infrastructure Design Plan.pptx
wondimagegndesta
 
Agentic Automation - Delhi UiPath Community Meetup
Agentic Automation - Delhi UiPath Community MeetupAgentic Automation - Delhi UiPath Community Meetup
Agentic Automation - Delhi UiPath Community Meetup
Manoj Batra (1600 + Connections)
 
Mastering Testing in the Modern F&B Landscape
Mastering Testing in the Modern F&B LandscapeMastering Testing in the Modern F&B Landscape
Mastering Testing in the Modern F&B Landscape
marketing943205
 
Zilliz Cloud Monthly Technical Review: May 2025
Zilliz Cloud Monthly Technical Review: May 2025Zilliz Cloud Monthly Technical Review: May 2025
Zilliz Cloud Monthly Technical Review: May 2025
Zilliz
 
Artificial_Intelligence_in_Everyday_Life.pptx
Artificial_Intelligence_in_Everyday_Life.pptxArtificial_Intelligence_in_Everyday_Life.pptx
Artificial_Intelligence_in_Everyday_Life.pptx
03ANMOLCHAURASIYA
 
On-Device or Remote? On the Energy Efficiency of Fetching LLM-Generated Conte...
On-Device or Remote? On the Energy Efficiency of Fetching LLM-Generated Conte...On-Device or Remote? On the Energy Efficiency of Fetching LLM-Generated Conte...
On-Device or Remote? On the Energy Efficiency of Fetching LLM-Generated Conte...
Ivano Malavolta
 
May Patch Tuesday
May Patch TuesdayMay Patch Tuesday
May Patch Tuesday
Ivanti
 
Limecraft Webinar - 2025.3 release, featuring Content Delivery, Graphic Conte...
Limecraft Webinar - 2025.3 release, featuring Content Delivery, Graphic Conte...Limecraft Webinar - 2025.3 release, featuring Content Delivery, Graphic Conte...
Limecraft Webinar - 2025.3 release, featuring Content Delivery, Graphic Conte...
Maarten Verwaest
 
Unlocking Generative AI in your Web Apps
Unlocking Generative AI in your Web AppsUnlocking Generative AI in your Web Apps
Unlocking Generative AI in your Web Apps
Maximiliano Firtman
 
Kit-Works Team Study_아직도 Dockefile.pdf_김성호
Kit-Works Team Study_아직도 Dockefile.pdf_김성호Kit-Works Team Study_아직도 Dockefile.pdf_김성호
Kit-Works Team Study_아직도 Dockefile.pdf_김성호
Wonjun Hwang
 
The No-Code Way to Build a Marketing Team with One AI Agent (Download the n8n...
The No-Code Way to Build a Marketing Team with One AI Agent (Download the n8n...The No-Code Way to Build a Marketing Team with One AI Agent (Download the n8n...
The No-Code Way to Build a Marketing Team with One AI Agent (Download the n8n...
SOFTTECHHUB
 
Everything You Need to Know About Agentforce? (Put AI Agents to Work)
Everything You Need to Know About Agentforce? (Put AI Agents to Work)Everything You Need to Know About Agentforce? (Put AI Agents to Work)
Everything You Need to Know About Agentforce? (Put AI Agents to Work)
Cyntexa
 
IT488 Wireless Sensor Networks_Information Technology
IT488 Wireless Sensor Networks_Information TechnologyIT488 Wireless Sensor Networks_Information Technology
IT488 Wireless Sensor Networks_Information Technology
SHEHABALYAMANI
 
Com fer un pla de gestió de dades amb l'eiNa DMP (en anglès)
Com fer un pla de gestió de dades amb l'eiNa DMP (en anglès)Com fer un pla de gestió de dades amb l'eiNa DMP (en anglès)
Com fer un pla de gestió de dades amb l'eiNa DMP (en anglès)
CSUC - Consorci de Serveis Universitaris de Catalunya
 
Top-AI-Based-Tools-for-Game-Developers (1).pptx
Top-AI-Based-Tools-for-Game-Developers (1).pptxTop-AI-Based-Tools-for-Game-Developers (1).pptx
Top-AI-Based-Tools-for-Game-Developers (1).pptx
BR Softech
 
Could Virtual Threads cast away the usage of Kotlin Coroutines - DevoxxUK2025
Could Virtual Threads cast away the usage of Kotlin Coroutines - DevoxxUK2025Could Virtual Threads cast away the usage of Kotlin Coroutines - DevoxxUK2025
Could Virtual Threads cast away the usage of Kotlin Coroutines - DevoxxUK2025
João Esperancinha
 
Cybersecurity Threat Vectors and Mitigation
Cybersecurity Threat Vectors and MitigationCybersecurity Threat Vectors and Mitigation
Cybersecurity Threat Vectors and Mitigation
VICTOR MAESTRE RAMIREZ
 
IT484 Cyber Forensics_Information Technology
IT484 Cyber Forensics_Information TechnologyIT484 Cyber Forensics_Information Technology
IT484 Cyber Forensics_Information Technology
SHEHABALYAMANI
 
How to Install & Activate ListGrabber - eGrabber
How to Install & Activate ListGrabber - eGrabberHow to Install & Activate ListGrabber - eGrabber
How to Install & Activate ListGrabber - eGrabber
eGrabber
 
Crazy Incentives and How They Kill Security. How Do You Turn the Wheel?
Crazy Incentives and How They Kill Security. How Do You Turn the Wheel?Crazy Incentives and How They Kill Security. How Do You Turn the Wheel?
Crazy Incentives and How They Kill Security. How Do You Turn the Wheel?
Christian Folini
 
Developing System Infrastructure Design Plan.pptx
Developing System Infrastructure Design Plan.pptxDeveloping System Infrastructure Design Plan.pptx
Developing System Infrastructure Design Plan.pptx
wondimagegndesta
 
Mastering Testing in the Modern F&B Landscape
Mastering Testing in the Modern F&B LandscapeMastering Testing in the Modern F&B Landscape
Mastering Testing in the Modern F&B Landscape
marketing943205
 
Zilliz Cloud Monthly Technical Review: May 2025
Zilliz Cloud Monthly Technical Review: May 2025Zilliz Cloud Monthly Technical Review: May 2025
Zilliz Cloud Monthly Technical Review: May 2025
Zilliz
 
Artificial_Intelligence_in_Everyday_Life.pptx
Artificial_Intelligence_in_Everyday_Life.pptxArtificial_Intelligence_in_Everyday_Life.pptx
Artificial_Intelligence_in_Everyday_Life.pptx
03ANMOLCHAURASIYA
 
On-Device or Remote? On the Energy Efficiency of Fetching LLM-Generated Conte...
On-Device or Remote? On the Energy Efficiency of Fetching LLM-Generated Conte...On-Device or Remote? On the Energy Efficiency of Fetching LLM-Generated Conte...
On-Device or Remote? On the Energy Efficiency of Fetching LLM-Generated Conte...
Ivano Malavolta
 
May Patch Tuesday
May Patch TuesdayMay Patch Tuesday
May Patch Tuesday
Ivanti
 
Limecraft Webinar - 2025.3 release, featuring Content Delivery, Graphic Conte...
Limecraft Webinar - 2025.3 release, featuring Content Delivery, Graphic Conte...Limecraft Webinar - 2025.3 release, featuring Content Delivery, Graphic Conte...
Limecraft Webinar - 2025.3 release, featuring Content Delivery, Graphic Conte...
Maarten Verwaest
 
Unlocking Generative AI in your Web Apps
Unlocking Generative AI in your Web AppsUnlocking Generative AI in your Web Apps
Unlocking Generative AI in your Web Apps
Maximiliano Firtman
 
Kit-Works Team Study_아직도 Dockefile.pdf_김성호
Kit-Works Team Study_아직도 Dockefile.pdf_김성호Kit-Works Team Study_아직도 Dockefile.pdf_김성호
Kit-Works Team Study_아직도 Dockefile.pdf_김성호
Wonjun Hwang
 
The No-Code Way to Build a Marketing Team with One AI Agent (Download the n8n...
The No-Code Way to Build a Marketing Team with One AI Agent (Download the n8n...The No-Code Way to Build a Marketing Team with One AI Agent (Download the n8n...
The No-Code Way to Build a Marketing Team with One AI Agent (Download the n8n...
SOFTTECHHUB
 
Everything You Need to Know About Agentforce? (Put AI Agents to Work)
Everything You Need to Know About Agentforce? (Put AI Agents to Work)Everything You Need to Know About Agentforce? (Put AI Agents to Work)
Everything You Need to Know About Agentforce? (Put AI Agents to Work)
Cyntexa
 
IT488 Wireless Sensor Networks_Information Technology
IT488 Wireless Sensor Networks_Information TechnologyIT488 Wireless Sensor Networks_Information Technology
IT488 Wireless Sensor Networks_Information Technology
SHEHABALYAMANI
 
Ad

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
  翻译: