Debugging and Testing - Theory Notes
1. Debugging Techniques
Debugging is the process of identifying, analyzing, and removing errors (bugs) in a computer
program to ensure it behaves as expected.
Common Debugging Practices:
- Code Tracing: Reading the code step-by-step to understand the logic and identify errors.
- Print Debugging: Using output statements (like printf() in C) to display the values of variables and
program flow at various points.
- Backtracking: Re-examining the recent changes or steps in reverse order to find the cause of the
error.
- Binary Elimination: Dividing the code into parts and checking each part to locate the bug.
- Rubber Duck Debugging: Explaining the code to someone (or even an object) to help spot logical
mistakes.
Use of Debugging Tools:
- GDB (GNU Debugger): A powerful tool for debugging C/C++ programs. It allows the programmer
to:
- Set breakpoints
- Step through the program line by line
- Inspect variable values and memory content
- IDE Debuggers: Many Integrated Development Environments (IDEs) like Code::Blocks, Eclipse, or
Visual Studio provide built-in graphical debugging tools.
2. Testing
Testing is the process of verifying that a program works correctly and produces the expected output
for various inputs. It helps in finding errors before the software is released.
Writing Test Cases:
- A test case consists of a specific input and the expected output.
- It checks whether a function or program behaves as intended.
- Test cases should cover:
- Valid inputs
- Boundary values (e.g., maximum/minimum values)
- Invalid or unexpected inputs
Unit Testing:
- Unit testing is the process of testing individual functions or components of a program in isolation.
- It helps detect and fix bugs early in development.
- Each function is tested independently with multiple test cases.
- In C, unit testing can be done manually or using libraries like CUnit.
Conclusion:
Debugging and testing are essential in software development. Debugging ensures the removal of
errors, while testing verifies that the program produces correct and reliable output. Both are
necessary to build a stable and error-free application.
Sample C Program:
Example C Program for Testing and Debugging:
#include <stdio.h>
// Function to add two integers
int add(int a, int b) {
return a + b;
}
int main() {
int result;
// Test case 1
result = add(2, 3);
printf("Test 1 - Expected: 5, Got: %d\n", result);
// Test case 2
result = add(-1, 4);
printf("Test 2 - Expected: 3, Got: %d\n", result);
// Test case 3
result = add(0, 0);
printf("Test 3 - Expected: 0, Got: %d\n", result);
return 0;
}