SlideShare une entreprise Scribd logo
1  sur  23
Debugging
Michael Heron
Introduction
• In the last lecture we talked about how to find
flaws in computer programs.
• Or at least, find that there are flaws.
• In this lecture we are going to look at strategies
for actually locating the errors.
• A more subtle skill.
• Debugging a program occurs in two locations.
• Compile time (fixing syntax errors)
• Run time (fixing logic errors)
Syntax Errors
• C++ error messages are tremendously unhelpful.
• They are useful for people who already know why their code
won’t compile.
• Luckily syntax errors are the easiest kind of errors to locate.
• The compiler usually knows, to a degree, where the code has
fallen down.
Compiler Errors
• The key piece of information is the line number.
• That’s what narrows down our search.
• Code in C++ has a very strict syntax.
• Deviations from this syntax are not tolerated.
• Eventually it becomes second nature to identify
a syntax error.
• Humans are very good at pattern recognition.
• Until then, need to rely on examples.
• Lectures have these, as do your previous programs.
Logic Errors
• Logic errors are much more difficult to find.
• Your program runs, but it doesn’t do what it’s
supposed to do.
• A certain kind of mindset is required to be able
to find why code doesn’t work.
• Must be patient.
• For complex programs, it can take hours to track down
a single annoying bug.
• Must be willing to experiment.
• Sometimes errors only reveal clues when the code is
subtly changed.
Logic Errors
• First of all, it’s important to understand what you think the
program is doing.
• This won’t necessarily be what it is actually doing.
• Pen and paper important here.
• Trace the activity of each line of code.
• Like we do in the lectures and the tutorials.
• Draw the flow of logic through the program.
• Represent the state of all variables.
• See where they are modified.
Logic Errors
• Once you understand what you think the program is doing,
find out what the program is actually doing.
• We can put in debug statements throughout our code to trace
the flow of logic.
• Simply using cout to print the contents of variables at key
parts of the program can be invaluable.
• You can see when things aren’t doing what they should be doing.
The Visual Studio Debugger
• Visual studio has a powerful debugger built into it.
• It lets us follow the exact operation of the computer at each
stage of its execution.
• However, also important to learn how to do it without the
debugger.
• It’s not always available when you code.
• In fact, good debuggers are unusual in most programming
environments.
Detectin’
• There’s a multi-step process we go through to find errors.
• Reproduce the error
• So very important!
• Use lots and lots of debugging messages
• Simplify
• Try things
• Understand why it’s not working
• Don’t just fix it
Reproducing An Error
• The most important thing when debugging is to be able to
reliably reproduce the error.
• The most frustrating kind of error is the one that only happens
sometimes.
• Sometimes it’s possible to put a band-aid solution on a
malfunctioning program.
• This will cause problems later on.
• Best to solve the underlying issue.
Reproducing an Error
• An effective testing strategy is the most important thing here.
• You need to direct your tests towards the areas where things are
likely to fail.
• It doesn’t have to be as formal as defining actual test cases.
• Although that can help.
• If you can isolate the problem to a specific function, try a test
harness.
Example Test Harness
int main() {
int test_x[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
int test_y[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
int expected[] = {2, 4, 6, 8, 10, 12, 14, 16, 18, 20};
int tmp;
for (int i = 0; i < 10; i++) {
tmp = add_nums (test_x[i], test_y[i]);
if (tmp != expected[i]) {
cout << "Error in inputs: " << test_x[i] << ", " << test_y[i]
<< ". Expected " << expected[i] << ", got " << tmp << endl;
}
}
cout << "Testing concluded." << endl;
}
Example Output
Error in inputs: 1, 1. Expected 2, got 1
Error in inputs: 3, 3. Expected 6, got 9
Error in inputs: 4, 4. Expected 8, got 16
Error in inputs: 5, 5. Expected 10, got 25
Error in inputs: 6, 6. Expected 12, got 36
Error in inputs: 7, 7. Expected 14, got 49
Error in inputs: 8, 8. Expected 16, got 64
Error in inputs: 9, 9. Expected 18, got 81
Error in inputs: 10, 10. Expected 20, got 100
Testing concluded.
What’s the likely error here?
Use Debugging Messages
• When you have found where the error is, put
lots of debugging messages in.
• Simple cout statements that contain the value of
variables.
• Label these clearly
• You need to be able to see where they are coming
from at each part of the program.
• You can get rid of them when you are done.
• Comment out rather than delete.
• You may need them again later.
Simplify
• Sometimes there’s just too much code to work out what is
going wrong.
• Important to simplify a program when this is occuring.
• Comment out lines of code that are doing complex functionality.
• Replace them with simpler versions for testing
• For example, if you have a line of code generating a random
number…
• … replace it with a non random number for testing.
Experimentation
• The next phase is simply to experiment with the code.
• Change and tweak values to see if it makes a different.
• Your process up to this point will give you some code where
there are likely problems.
• Focus your testing around there.
Understanding
• Having found the bug, it’s tempting to just fix it.
• Not a great idea, understanding why bugs occur is how you
become a better programmer.
• Don’t simply recast the code.
• Work out why the code as it stands doesn’t work.
• This is transferable knowledge.
The Wrong Approach
for (int i = 0; i < someVariable; i++) {
}
for (int i = 0; i < someVariable - 1; i++) {
}
Your patient detecting has discovered the loop iterates one more time than
it should. The easy solution is to simply make it loop one less time. But…
that’s not the actual problem.
The problem is that you expected the loop to occur less frequently than it
did. It’s a symptom of a larger problem (the code isn’t doing what you think
it is), and a quick fix like this will leave problems unsolved for the future.
A Debugging Exercise
int main() {
int num, num2;
int ans;
num = get_input ("Give me a number");
num2 = get_input ("Give me the power you want that number to");
ans = calculate_power (num, num);
display_answer (ans);
return 0;
}
Get Input
int get_input (string str) {
int tmp;
cout << str;
cin >> tmp;
return tmp;
}
Calculate Power
int calculate_power (int num1, int num2)
{
int total = 0;
for (int i = 0; i <= num2; i++) {
total = total * num1;
}
return total;
}
Display Answer
void display_answer (int x) {
cout << "The answer is " << x
<< endl;
}
This program compiles fine.
It doesn’t give the right output.
Where is the error?
Need a process to find it!
Summary
• Getting programs to compile is part of the battle.
• The bigger battle is – making it work properly
when it does.
• This needs a particular kind of mindset to do.
• Bugs don’t get fixed instantly, they need a lot of
figuring out in larger programs.
• Important to understand why errors occur.
• That’s how you get better at programming generally.

Contenu connexe

Tendances

Exception handling in c programming
Exception handling in c programmingException handling in c programming
Exception handling in c programmingRaza Najam
 
Exception handling in c++ by manoj vasava
Exception handling in c++ by manoj vasavaException handling in c++ by manoj vasava
Exception handling in c++ by manoj vasavaManoj_vasava
 
Error handling and debugging
Error handling and debuggingError handling and debugging
Error handling and debuggingsalissal
 
Basic Flowcharting
Basic FlowchartingBasic Flowcharting
Basic Flowchartingsebrown
 
Why Students Need the CppCat Code Analyzer
Why Students Need the CppCat Code AnalyzerWhy Students Need the CppCat Code Analyzer
Why Students Need the CppCat Code AnalyzerPVS-Studio
 
Programming basics
Programming basicsProgramming basics
Programming basicsillidari
 
Exception handling in c++
Exception handling in c++Exception handling in c++
Exception handling in c++imran khan
 
03 algorithm properties
03 algorithm properties03 algorithm properties
03 algorithm propertiesLincoln School
 
Unit 3 Foc
Unit  3 FocUnit  3 Foc
Unit 3 FocJAYA
 
Computer Programming, Loops using Java
Computer Programming, Loops using JavaComputer Programming, Loops using Java
Computer Programming, Loops using JavaMahmoud Alfarra
 

Tendances (18)

phases of algorithm
phases of algorithmphases of algorithm
phases of algorithm
 
Class 9 Lecture Notes
Class 9 Lecture NotesClass 9 Lecture Notes
Class 9 Lecture Notes
 
Debugging in .Net
Debugging in .NetDebugging in .Net
Debugging in .Net
 
Class 8 Lecture Notes
Class 8 Lecture NotesClass 8 Lecture Notes
Class 8 Lecture Notes
 
Exception handling in c programming
Exception handling in c programmingException handling in c programming
Exception handling in c programming
 
Exception handling in c++ by manoj vasava
Exception handling in c++ by manoj vasavaException handling in c++ by manoj vasava
Exception handling in c++ by manoj vasava
 
Error handling and debugging
Error handling and debuggingError handling and debugging
Error handling and debugging
 
Pseudocode
PseudocodePseudocode
Pseudocode
 
Basic Flowcharting
Basic FlowchartingBasic Flowcharting
Basic Flowcharting
 
Why Students Need the CppCat Code Analyzer
Why Students Need the CppCat Code AnalyzerWhy Students Need the CppCat Code Analyzer
Why Students Need the CppCat Code Analyzer
 
Programming basics
Programming basicsProgramming basics
Programming basics
 
Exception handling in c++
Exception handling in c++Exception handling in c++
Exception handling in c++
 
Pseudocode
PseudocodePseudocode
Pseudocode
 
2 debugging-c
2 debugging-c2 debugging-c
2 debugging-c
 
03 algorithm properties
03 algorithm properties03 algorithm properties
03 algorithm properties
 
Unit 3 Foc
Unit  3 FocUnit  3 Foc
Unit 3 Foc
 
03b loops
03b   loops03b   loops
03b loops
 
Computer Programming, Loops using Java
Computer Programming, Loops using JavaComputer Programming, Loops using Java
Computer Programming, Loops using Java
 

En vedette

En vedette (12)

Diabetes prevention and natural treatment
Diabetes prevention and natural treatmentDiabetes prevention and natural treatment
Diabetes prevention and natural treatment
 
Corn pickflick
Corn pickflickCorn pickflick
Corn pickflick
 
Dental Web Marketing Success With LinkedIn
Dental Web Marketing Success With LinkedInDental Web Marketing Success With LinkedIn
Dental Web Marketing Success With LinkedIn
 
20140531 serebryany lecture02_find_scary_cpp_bugs
20140531 serebryany lecture02_find_scary_cpp_bugs20140531 serebryany lecture02_find_scary_cpp_bugs
20140531 serebryany lecture02_find_scary_cpp_bugs
 
Sandalias neur
Sandalias neurSandalias neur
Sandalias neur
 
Puppet script the parble scrip[
Puppet script  the parble scrip[Puppet script  the parble scrip[
Puppet script the parble scrip[
 
Q2.12: Debugging with GDB
Q2.12: Debugging with GDBQ2.12: Debugging with GDB
Q2.12: Debugging with GDB
 
Debugging and Profiling C++ Template Metaprograms
Debugging and Profiling C++ Template MetaprogramsDebugging and Profiling C++ Template Metaprograms
Debugging and Profiling C++ Template Metaprograms
 
Avoiding pitfalls of bad slides
Avoiding pitfalls of bad slidesAvoiding pitfalls of bad slides
Avoiding pitfalls of bad slides
 
Loops
LoopsLoops
Loops
 
Loops in C
Loops in CLoops in C
Loops in C
 
C++ loop
C++ loop C++ loop
C++ loop
 

Similaire à CPP10 - Debugging

Dev buchan 30 proven tips
Dev buchan 30 proven tipsDev buchan 30 proven tips
Dev buchan 30 proven tipsBill Buchan
 
How to complement TDD with static analysis
How to complement TDD with static analysisHow to complement TDD with static analysis
How to complement TDD with static analysisPVS-Studio
 
CODE TUNINGtertertertrtryryryryrtytrytrtry
CODE TUNINGtertertertrtryryryryrtytrytrtryCODE TUNINGtertertertrtryryryryrtytrytrtry
CODE TUNINGtertertertrtryryryryrtytrytrtrykapib57390
 
TDD reloaded - JUGTAA 24 Ottobre 2012
TDD reloaded - JUGTAA 24 Ottobre 2012TDD reloaded - JUGTAA 24 Ottobre 2012
TDD reloaded - JUGTAA 24 Ottobre 2012Pietro Di Bello
 
Lecture 3.1.1 Try Throw Catch.pptx
Lecture 3.1.1 Try Throw Catch.pptxLecture 3.1.1 Try Throw Catch.pptx
Lecture 3.1.1 Try Throw Catch.pptxsunilsoni446112
 
Lecture 1 Try Throw Catch.pptx
Lecture 1 Try Throw Catch.pptxLecture 1 Try Throw Catch.pptx
Lecture 1 Try Throw Catch.pptxVishuSaini22
 
Algorithm and C code related to data structure
Algorithm and C code related to data structureAlgorithm and C code related to data structure
Algorithm and C code related to data structureSelf-Employed
 
Test-Driven Development
 Test-Driven Development  Test-Driven Development
Test-Driven Development Amir Assad
 
Introduzione allo Unit Testing
Introduzione allo Unit TestingIntroduzione allo Unit Testing
Introduzione allo Unit TestingStefano Ottaviani
 
iOS Test-Driven Development
iOS Test-Driven DevelopmentiOS Test-Driven Development
iOS Test-Driven DevelopmentPablo Villar
 
assertYourself - Breaking the Theories and Assumptions of Unit Testing in Flex
assertYourself - Breaking the Theories and Assumptions of Unit Testing in FlexassertYourself - Breaking the Theories and Assumptions of Unit Testing in Flex
assertYourself - Breaking the Theories and Assumptions of Unit Testing in Flexmichael.labriola
 
Accord.Net: Looking for a Bug that Could Help Machines Conquer Humankind
Accord.Net: Looking for a Bug that Could Help Machines Conquer HumankindAccord.Net: Looking for a Bug that Could Help Machines Conquer Humankind
Accord.Net: Looking for a Bug that Could Help Machines Conquer HumankindPVS-Studio
 
The limits of unit testing by Craig Stuntz
The limits of unit testing by Craig StuntzThe limits of unit testing by Craig Stuntz
The limits of unit testing by Craig StuntzQA or the Highway
 
The Limits of Unit Testing by Craig Stuntz
The Limits of Unit Testing by Craig StuntzThe Limits of Unit Testing by Craig Stuntz
The Limits of Unit Testing by Craig StuntzQA or the Highway
 
ProgFund_Lecture7_Programming_Algorithm.pdf
ProgFund_Lecture7_Programming_Algorithm.pdfProgFund_Lecture7_Programming_Algorithm.pdf
ProgFund_Lecture7_Programming_Algorithm.pdflailoesakhan
 

Similaire à CPP10 - Debugging (20)

Dev buchan 30 proven tips
Dev buchan 30 proven tipsDev buchan 30 proven tips
Dev buchan 30 proven tips
 
How to complement TDD with static analysis
How to complement TDD with static analysisHow to complement TDD with static analysis
How to complement TDD with static analysis
 
CODE TUNINGtertertertrtryryryryrtytrytrtry
CODE TUNINGtertertertrtryryryryrtytrytrtryCODE TUNINGtertertertrtryryryryrtytrytrtry
CODE TUNINGtertertertrtryryryryrtytrytrtry
 
Debugging
DebuggingDebugging
Debugging
 
TDD reloaded - JUGTAA 24 Ottobre 2012
TDD reloaded - JUGTAA 24 Ottobre 2012TDD reloaded - JUGTAA 24 Ottobre 2012
TDD reloaded - JUGTAA 24 Ottobre 2012
 
Introduction to C ++.pptx
Introduction to C ++.pptxIntroduction to C ++.pptx
Introduction to C ++.pptx
 
Lecture 3.1.1 Try Throw Catch.pptx
Lecture 3.1.1 Try Throw Catch.pptxLecture 3.1.1 Try Throw Catch.pptx
Lecture 3.1.1 Try Throw Catch.pptx
 
Lecture 1 Try Throw Catch.pptx
Lecture 1 Try Throw Catch.pptxLecture 1 Try Throw Catch.pptx
Lecture 1 Try Throw Catch.pptx
 
CPP03 - Repetition
CPP03 - RepetitionCPP03 - Repetition
CPP03 - Repetition
 
Algorithm and C code related to data structure
Algorithm and C code related to data structureAlgorithm and C code related to data structure
Algorithm and C code related to data structure
 
Test-Driven Development
 Test-Driven Development  Test-Driven Development
Test-Driven Development
 
Introduzione allo Unit Testing
Introduzione allo Unit TestingIntroduzione allo Unit Testing
Introduzione allo Unit Testing
 
Algorithm.pdf
Algorithm.pdfAlgorithm.pdf
Algorithm.pdf
 
iOS Test-Driven Development
iOS Test-Driven DevelopmentiOS Test-Driven Development
iOS Test-Driven Development
 
assertYourself - Breaking the Theories and Assumptions of Unit Testing in Flex
assertYourself - Breaking the Theories and Assumptions of Unit Testing in FlexassertYourself - Breaking the Theories and Assumptions of Unit Testing in Flex
assertYourself - Breaking the Theories and Assumptions of Unit Testing in Flex
 
TDD a piccoli passi
TDD a piccoli passiTDD a piccoli passi
TDD a piccoli passi
 
Accord.Net: Looking for a Bug that Could Help Machines Conquer Humankind
Accord.Net: Looking for a Bug that Could Help Machines Conquer HumankindAccord.Net: Looking for a Bug that Could Help Machines Conquer Humankind
Accord.Net: Looking for a Bug that Could Help Machines Conquer Humankind
 
The limits of unit testing by Craig Stuntz
The limits of unit testing by Craig StuntzThe limits of unit testing by Craig Stuntz
The limits of unit testing by Craig Stuntz
 
The Limits of Unit Testing by Craig Stuntz
The Limits of Unit Testing by Craig StuntzThe Limits of Unit Testing by Craig Stuntz
The Limits of Unit Testing by Craig Stuntz
 
ProgFund_Lecture7_Programming_Algorithm.pdf
ProgFund_Lecture7_Programming_Algorithm.pdfProgFund_Lecture7_Programming_Algorithm.pdf
ProgFund_Lecture7_Programming_Algorithm.pdf
 

Plus de Michael Heron

Meeple centred design - Board Game Accessibility
Meeple centred design - Board Game AccessibilityMeeple centred design - Board Game Accessibility
Meeple centred design - Board Game AccessibilityMichael Heron
 
Musings on misconduct
Musings on misconductMusings on misconduct
Musings on misconductMichael Heron
 
Accessibility Support with the ACCESS Framework
Accessibility Support with the ACCESS FrameworkAccessibility Support with the ACCESS Framework
Accessibility Support with the ACCESS FrameworkMichael Heron
 
ACCESS: A Technical Framework for Adaptive Accessibility Support
ACCESS:  A Technical Framework for Adaptive Accessibility SupportACCESS:  A Technical Framework for Adaptive Accessibility Support
ACCESS: A Technical Framework for Adaptive Accessibility SupportMichael Heron
 
Authorship and Autership
Authorship and AutershipAuthorship and Autership
Authorship and AutershipMichael Heron
 
Text parser based interaction
Text parser based interactionText parser based interaction
Text parser based interactionMichael Heron
 
GRPHICS08 - Raytracing and Radiosity
GRPHICS08 - Raytracing and RadiosityGRPHICS08 - Raytracing and Radiosity
GRPHICS08 - Raytracing and RadiosityMichael Heron
 
GRPHICS07 - Textures
GRPHICS07 - TexturesGRPHICS07 - Textures
GRPHICS07 - TexturesMichael Heron
 
GRPHICS05 - Rendering (2)
GRPHICS05 - Rendering (2)GRPHICS05 - Rendering (2)
GRPHICS05 - Rendering (2)Michael Heron
 
GRPHICS04 - Rendering (1)
GRPHICS04 - Rendering (1)GRPHICS04 - Rendering (1)
GRPHICS04 - Rendering (1)Michael Heron
 
GRPHICS03 - Graphical Representation
GRPHICS03 - Graphical RepresentationGRPHICS03 - Graphical Representation
GRPHICS03 - Graphical RepresentationMichael Heron
 
GRPHICS02 - Creating 3D Graphics
GRPHICS02 - Creating 3D GraphicsGRPHICS02 - Creating 3D Graphics
GRPHICS02 - Creating 3D GraphicsMichael Heron
 
GRPHICS01 - Introduction to 3D Graphics
GRPHICS01 - Introduction to 3D GraphicsGRPHICS01 - Introduction to 3D Graphics
GRPHICS01 - Introduction to 3D GraphicsMichael Heron
 
GRPHICS09 - Art Appreciation
GRPHICS09 - Art AppreciationGRPHICS09 - Art Appreciation
GRPHICS09 - Art AppreciationMichael Heron
 

Plus de Michael Heron (20)

Meeple centred design - Board Game Accessibility
Meeple centred design - Board Game AccessibilityMeeple centred design - Board Game Accessibility
Meeple centred design - Board Game Accessibility
 
Musings on misconduct
Musings on misconductMusings on misconduct
Musings on misconduct
 
Accessibility Support with the ACCESS Framework
Accessibility Support with the ACCESS FrameworkAccessibility Support with the ACCESS Framework
Accessibility Support with the ACCESS Framework
 
ACCESS: A Technical Framework for Adaptive Accessibility Support
ACCESS:  A Technical Framework for Adaptive Accessibility SupportACCESS:  A Technical Framework for Adaptive Accessibility Support
ACCESS: A Technical Framework for Adaptive Accessibility Support
 
Authorship and Autership
Authorship and AutershipAuthorship and Autership
Authorship and Autership
 
Text parser based interaction
Text parser based interactionText parser based interaction
Text parser based interaction
 
SAD04 - Inheritance
SAD04 - InheritanceSAD04 - Inheritance
SAD04 - Inheritance
 
GRPHICS08 - Raytracing and Radiosity
GRPHICS08 - Raytracing and RadiosityGRPHICS08 - Raytracing and Radiosity
GRPHICS08 - Raytracing and Radiosity
 
GRPHICS07 - Textures
GRPHICS07 - TexturesGRPHICS07 - Textures
GRPHICS07 - Textures
 
GRPHICS06 - Shading
GRPHICS06 - ShadingGRPHICS06 - Shading
GRPHICS06 - Shading
 
GRPHICS05 - Rendering (2)
GRPHICS05 - Rendering (2)GRPHICS05 - Rendering (2)
GRPHICS05 - Rendering (2)
 
GRPHICS04 - Rendering (1)
GRPHICS04 - Rendering (1)GRPHICS04 - Rendering (1)
GRPHICS04 - Rendering (1)
 
GRPHICS03 - Graphical Representation
GRPHICS03 - Graphical RepresentationGRPHICS03 - Graphical Representation
GRPHICS03 - Graphical Representation
 
GRPHICS02 - Creating 3D Graphics
GRPHICS02 - Creating 3D GraphicsGRPHICS02 - Creating 3D Graphics
GRPHICS02 - Creating 3D Graphics
 
GRPHICS01 - Introduction to 3D Graphics
GRPHICS01 - Introduction to 3D GraphicsGRPHICS01 - Introduction to 3D Graphics
GRPHICS01 - Introduction to 3D Graphics
 
GRPHICS09 - Art Appreciation
GRPHICS09 - Art AppreciationGRPHICS09 - Art Appreciation
GRPHICS09 - Art Appreciation
 
2CPP18 - Modifiers
2CPP18 - Modifiers2CPP18 - Modifiers
2CPP18 - Modifiers
 
2CPP17 - File IO
2CPP17 - File IO2CPP17 - File IO
2CPP17 - File IO
 
2CPP16 - STL
2CPP16 - STL2CPP16 - STL
2CPP16 - STL
 
2CPP15 - Templates
2CPP15 - Templates2CPP15 - Templates
2CPP15 - Templates
 

Dernier

5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdfWave PLM
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxComplianceQuest1
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsArshad QA
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfkalichargn70th171
 
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AISyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AIABDERRAOUF MEHENNI
 
Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...OnePlan Solutions
 
Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionSolGuruz
 
Test Automation Strategy for Frontend and Backend
Test Automation Strategy for Frontend and BackendTest Automation Strategy for Frontend and Backend
Test Automation Strategy for Frontend and BackendArshad QA
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...MyIntelliSource, Inc.
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...harshavardhanraghave
 
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...gurkirankumar98700
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantAxelRicardoTrocheRiq
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...ICS
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...MyIntelliSource, Inc.
 
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️anilsa9823
 
What is Binary Language? Computer Number Systems
What is Binary Language?  Computer Number SystemsWhat is Binary Language?  Computer Number Systems
What is Binary Language? Computer Number SystemsJheuzeDellosa
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxbodapatigopi8531
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVshikhaohhpro
 
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...OnePlan Solutions
 

Dernier (20)

5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docx
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview Questions
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
 
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AISyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
 
Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...
 
Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with Precision
 
Test Automation Strategy for Frontend and Backend
Test Automation Strategy for Frontend and BackendTest Automation Strategy for Frontend and Backend
Test Automation Strategy for Frontend and Backend
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
 
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service Consultant
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
 
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
 
What is Binary Language? Computer Number Systems
What is Binary Language?  Computer Number SystemsWhat is Binary Language?  Computer Number Systems
What is Binary Language? Computer Number Systems
 
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS LiveVip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptx
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTV
 
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
 

CPP10 - Debugging

  • 2. Introduction • In the last lecture we talked about how to find flaws in computer programs. • Or at least, find that there are flaws. • In this lecture we are going to look at strategies for actually locating the errors. • A more subtle skill. • Debugging a program occurs in two locations. • Compile time (fixing syntax errors) • Run time (fixing logic errors)
  • 3. Syntax Errors • C++ error messages are tremendously unhelpful. • They are useful for people who already know why their code won’t compile. • Luckily syntax errors are the easiest kind of errors to locate. • The compiler usually knows, to a degree, where the code has fallen down.
  • 4. Compiler Errors • The key piece of information is the line number. • That’s what narrows down our search. • Code in C++ has a very strict syntax. • Deviations from this syntax are not tolerated. • Eventually it becomes second nature to identify a syntax error. • Humans are very good at pattern recognition. • Until then, need to rely on examples. • Lectures have these, as do your previous programs.
  • 5. Logic Errors • Logic errors are much more difficult to find. • Your program runs, but it doesn’t do what it’s supposed to do. • A certain kind of mindset is required to be able to find why code doesn’t work. • Must be patient. • For complex programs, it can take hours to track down a single annoying bug. • Must be willing to experiment. • Sometimes errors only reveal clues when the code is subtly changed.
  • 6. Logic Errors • First of all, it’s important to understand what you think the program is doing. • This won’t necessarily be what it is actually doing. • Pen and paper important here. • Trace the activity of each line of code. • Like we do in the lectures and the tutorials. • Draw the flow of logic through the program. • Represent the state of all variables. • See where they are modified.
  • 7. Logic Errors • Once you understand what you think the program is doing, find out what the program is actually doing. • We can put in debug statements throughout our code to trace the flow of logic. • Simply using cout to print the contents of variables at key parts of the program can be invaluable. • You can see when things aren’t doing what they should be doing.
  • 8. The Visual Studio Debugger • Visual studio has a powerful debugger built into it. • It lets us follow the exact operation of the computer at each stage of its execution. • However, also important to learn how to do it without the debugger. • It’s not always available when you code. • In fact, good debuggers are unusual in most programming environments.
  • 9. Detectin’ • There’s a multi-step process we go through to find errors. • Reproduce the error • So very important! • Use lots and lots of debugging messages • Simplify • Try things • Understand why it’s not working • Don’t just fix it
  • 10. Reproducing An Error • The most important thing when debugging is to be able to reliably reproduce the error. • The most frustrating kind of error is the one that only happens sometimes. • Sometimes it’s possible to put a band-aid solution on a malfunctioning program. • This will cause problems later on. • Best to solve the underlying issue.
  • 11. Reproducing an Error • An effective testing strategy is the most important thing here. • You need to direct your tests towards the areas where things are likely to fail. • It doesn’t have to be as formal as defining actual test cases. • Although that can help. • If you can isolate the problem to a specific function, try a test harness.
  • 12. Example Test Harness int main() { int test_x[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; int test_y[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; int expected[] = {2, 4, 6, 8, 10, 12, 14, 16, 18, 20}; int tmp; for (int i = 0; i < 10; i++) { tmp = add_nums (test_x[i], test_y[i]); if (tmp != expected[i]) { cout << "Error in inputs: " << test_x[i] << ", " << test_y[i] << ". Expected " << expected[i] << ", got " << tmp << endl; } } cout << "Testing concluded." << endl; }
  • 13. Example Output Error in inputs: 1, 1. Expected 2, got 1 Error in inputs: 3, 3. Expected 6, got 9 Error in inputs: 4, 4. Expected 8, got 16 Error in inputs: 5, 5. Expected 10, got 25 Error in inputs: 6, 6. Expected 12, got 36 Error in inputs: 7, 7. Expected 14, got 49 Error in inputs: 8, 8. Expected 16, got 64 Error in inputs: 9, 9. Expected 18, got 81 Error in inputs: 10, 10. Expected 20, got 100 Testing concluded. What’s the likely error here?
  • 14. Use Debugging Messages • When you have found where the error is, put lots of debugging messages in. • Simple cout statements that contain the value of variables. • Label these clearly • You need to be able to see where they are coming from at each part of the program. • You can get rid of them when you are done. • Comment out rather than delete. • You may need them again later.
  • 15. Simplify • Sometimes there’s just too much code to work out what is going wrong. • Important to simplify a program when this is occuring. • Comment out lines of code that are doing complex functionality. • Replace them with simpler versions for testing • For example, if you have a line of code generating a random number… • … replace it with a non random number for testing.
  • 16. Experimentation • The next phase is simply to experiment with the code. • Change and tweak values to see if it makes a different. • Your process up to this point will give you some code where there are likely problems. • Focus your testing around there.
  • 17. Understanding • Having found the bug, it’s tempting to just fix it. • Not a great idea, understanding why bugs occur is how you become a better programmer. • Don’t simply recast the code. • Work out why the code as it stands doesn’t work. • This is transferable knowledge.
  • 18. The Wrong Approach for (int i = 0; i < someVariable; i++) { } for (int i = 0; i < someVariable - 1; i++) { } Your patient detecting has discovered the loop iterates one more time than it should. The easy solution is to simply make it loop one less time. But… that’s not the actual problem. The problem is that you expected the loop to occur less frequently than it did. It’s a symptom of a larger problem (the code isn’t doing what you think it is), and a quick fix like this will leave problems unsolved for the future.
  • 19. A Debugging Exercise int main() { int num, num2; int ans; num = get_input ("Give me a number"); num2 = get_input ("Give me the power you want that number to"); ans = calculate_power (num, num); display_answer (ans); return 0; }
  • 20. Get Input int get_input (string str) { int tmp; cout << str; cin >> tmp; return tmp; }
  • 21. Calculate Power int calculate_power (int num1, int num2) { int total = 0; for (int i = 0; i <= num2; i++) { total = total * num1; } return total; }
  • 22. Display Answer void display_answer (int x) { cout << "The answer is " << x << endl; } This program compiles fine. It doesn’t give the right output. Where is the error? Need a process to find it!
  • 23. Summary • Getting programs to compile is part of the battle. • The bigger battle is – making it work properly when it does. • This needs a particular kind of mindset to do. • Bugs don’t get fixed instantly, they need a lot of figuring out in larger programs. • Important to understand why errors occur. • That’s how you get better at programming generally.