SlideShare a Scribd company logo
1 of 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.

More Related Content

What's hot

Error handling and debugging
Error handling and debuggingError handling and debugging
Error handling and debugging
salissal
 
03 algorithm properties
03 algorithm properties03 algorithm properties
03 algorithm properties
Lincoln School
 

What's hot (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
 

Viewers also liked

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
Computer Science Club
 
Avoiding pitfalls of bad slides
Avoiding pitfalls of bad slidesAvoiding pitfalls of bad slides
Avoiding pitfalls of bad slides
brophyl
 

Viewers also liked (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
 

Similar to CPP10 - Debugging

Dev buchan 30 proven tips
Dev buchan 30 proven tipsDev buchan 30 proven tips
Dev buchan 30 proven tips
Bill Buchan
 
CODE TUNINGtertertertrtryryryryrtytrytrtry
CODE TUNINGtertertertrtryryryryrtytrytrtryCODE TUNINGtertertertrtryryryryrtytrytrtry
CODE TUNINGtertertertrtryryryryrtytrytrtry
kapib57390
 

Similar to 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
 

More from Michael Heron

More from 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
 

Recently uploaded

TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
mohitmore19
 

Recently uploaded (20)

Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
Direct Style Effect Systems -The Print[A] Example- A Comprehension AidDirect Style Effect Systems -The Print[A] Example- A Comprehension Aid
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
 
Introducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) SolutionIntroducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) Solution
 
8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students
 
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
 
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
 
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
 
Azure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdf
Azure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdfAzure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdf
Azure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdf
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview Questions
 
How to Choose the Right Laravel Development Partner in New York City_compress...
How to Choose the Right Laravel Development Partner in New York City_compress...How to Choose the Right Laravel Development Partner in New York City_compress...
How to Choose the Right Laravel Development Partner in New York City_compress...
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
 
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
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
 
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
 
Exploring the Best Video Editing App.pdf
Exploring the Best Video Editing App.pdfExploring the Best Video Editing App.pdf
Exploring the Best Video Editing App.pdf
 
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 ...
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial Goals
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Models
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
 

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.