12

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 9

Lab Title: Debugging Techniques in Programming

Objective:

The main goal of this lab is to familiarize students with effective debugging techniques to identify and
correct errors and logic flaws in a program.

Importance of Debugging in the Software Development Process in C++:

Debugging is a crucial aspect of the software development process in C++ as it plays a pivotal role in
ensuring the reliability and correctness of a program. Even the most seasoned developers encounter
errors in their code, and effective debugging is essential for identifying and rectifying these issues.
Debugging not only helps in eliminating errors but also enhances the overall quality of the code, making
it more efficient and maintainable.

Common Types of Errors in C++:

1. Syntax Errors:

- Syntax errors occur when the code violates the rules of the C++ language. These errors are typically
detected by the compiler during the compilation phase. Examples include missing semicolons,
mismatched parentheses, or incorrect variable declarations.

2. Runtime Errors:

- Runtime errors occur during the execution of the program. They often lead to program crashes or
unexpected behavior. Examples include division by zero, accessing an out-of-bounds array element, or
dereferencing a null pointer.

3. Logic Errors:

- Logic errors are more subtle and challenging to detect. They occur when the program's logic is flawed,
leading to incorrect results. Examples include incorrect algorithm implementation, flawed conditional
statements, or improper loop control.

Key Debugging Tools in C++:

1. Print Statements:

- The use of print statements (e.g., `cout` statements) is a simple yet effective way to trace the flow of
the program and inspect variable values during runtime.

cout << "Debugging point A" << endl;

// Print variable values

cout << "Variable x: " << x << endl;

2. Debugging Environments (e.g., GDB):


- Debugging environments, such as GDB (GNU Debugger), provide advanced debugging features. These
include setting breakpoints, stepping through code, and inspecting variable values interactively.

gdb ./your_program

(gdb) break main

(gdb) run

3. Version Control Systems (e.g., Git):

- Version control systems like Git allow developers to track changes in their codebase. This is valuable
for identifying when errors were introduced and for collaborating with other developers.

git commit -m "Fixed bug in function foo"

Common Debugging Techniques in C++:

a. Print Statements:

Using print statements, such as `cout` in C++, is a fundamental and straightforward method to
understand the flow of the program and inspect the values of variables at different points during
runtime.

Example:

#include <iostream>

Using namespace std;

int main() {

int x = 5;

cout << "Debugging point A" << endl;

// Print variable values

cout << "Variable x: " << x << endl;

// Your code logic

cout << "Debugging point B" << endl;

return 0;

Exercise: Given a C++ program with logical errors, use print statements strategically to identify and
correct the issues.

#include <iostream>
Using namespace std;

int main() {

// Logical error 1: Incorrect variable initialization

int x = 5;

int y = 0;

// Logical error 2: Incorrect loop condition

for (int i = 0; i <= 5; ++i) {

// Logical error 3: Incorrect calculation

y = x * i;

// Print statements to debug

cout << "i: " << i << endl;

cout << "x: " << x << endl;

cout << "y: " << y << endl;

// Logical error 4: Incorrect output

cout << "Result: " << x + y << endl;

// Logical error 5: Incorrect return statement

return 0;

In this example:

1. added print statements to display the values of variables (`i`, `x`, `y`) at different points in the program.

2. corrected the initialization of variables `x` and `y`.

3. adjusted the loop condition to make it more suitable.

4. corrected the calculation of the variable `y`.

5. fixed the output statement to display the correct result.

6. corrected the return statement.

By strategically placing print statements and analyzing the output, you can identify and correct logical
errors in your C++ program. Keep in mind that this is a simplified example, and in a real-world scenario,
you may encounter more complex issues that require a more in-depth debugging approach, possibly
using a debugger or more sophisticated logging techniques.
b. IDE Debugging Tools:

Integrated Development Environments (IDEs) provide powerful debugging tools that assist in identifying
and fixing errors more efficiently. Key features include setting breakpoints, stepping through code, and
inspecting variable values in real-time.

Example:

Using breakpoints in an IDE like Visual Studio Code:

1. Set a breakpoint by clicking in the gutter next to the line number.

2. Start debugging the program.

3. Execution will pause at the breakpoint, allowing you to inspect variable values.

Exercise: Debug a C++ program using breakpoints and step-by-step execution in your preferred IDE.

#include <iostream>

Using namespace std;

int main() {

int x = 5;

int y = 0;

for (int i = 1; i <= 5; ++i) {

y = x * i;

cout << "i: " << i << endl;

cout << "x: " << x << endl;

cout << "y: " << y << endl;

cout << "Result: " << x + y << endl;

return 0;

To debug a C++ program using breakpoints and step-by-step execution in Dev C++, follow these steps:
1. Open the Project:

- Open Dev C++.

- Open your C++ project.

2. Set a Breakpoint:

- Locate the line where you want to start debugging.

- Click on the left margin of the editor window at that line number. This sets a breakpoint.

3. Compile the Program with Debug Information:

- Ensure that you are compiling your program with debugging information. In Dev C++, this is typically
done by selecting a "Debug" build or ensuring that debugging information is included in your
compilation settings.

4. Start Debugging:

- Go to the "Run" menu and select "Start Debugging" or press F5.

5. Execution Pauses at Breakpoint:

- The program will start, and execution will pause at the line where you set the breakpoint.

6. Inspect Variables:

- You can now inspect the values of variables by hovering over them or by using the Watches window.

7. Step Through the Code:

- Use the debugging toolbar or the keyboard shortcuts to step through the code:

- Step Into (F7): Executes the current line and moves to the next line. If the current line is a function
call, it enters the function.

- Step Over (F8): Executes the current line. If the current line is a function call, it executes the entire
function and moves to the next line in the calling function.

- Step Out (Shift + F8): Executes the remaining lines of the current function and returns to the
calling function.
8. Continue Execution:

- If you want to run the program until the next breakpoint, select "Continue" from the debugging
toolbar or press F9.

9. Inspecting Call Stack:

- The call stack window shows you the current function calls. You can use this to trace the flow of your
program.

10. Watch Window:

- Use the Watch window to monitor the values of specific variables during execution.

11. Fix Issues:

- As you step through the code, you may identify the issues causing unexpected behavior. Fix them and
continue debugging until your program runs correctly.

12. Stop Debugging:

- Once you've fixed the issues, stop debugging by selecting "Stop Debugging" from the "Run" menu or
by pressing Shift + F5.

c. Logging:

Logging involves strategically placing log statements in the code to capture information about the
program's behavior during runtime. This can help track the flow of execution and identify unexpected
behavior.

Example:

#include <iostream>

#include <fstream>

void logMessage(const string& message) {

ofstream logFile("logfile.txt", ios::app);

logFile << message << endl;

logFile.close();
}

int main() {

logMessage("Program started");

// Your code logic

logMessage("Debugging point reached");

return 0;

Exercise: Implement logging in a C++ program and analyze the log output to identify and fix issues.

#include <iostream>

#include <fstream>

Using namespace std;

// Logging function

void logMessage(const string& message) {

// Open the log file in append mode

ofstream logfile("logfile.txt", ios::app);

// Write the message to the log file

logfile << message << endl;

// Close the log file

logfile.close();

int main() {

// Initialize variables

int x = 5;

int y = 0;

// Attempt to perform a division

logMessage("Attempting division...");

// Check for division by zero

if (y != 0) {
int result = x / y;

logMessage("Result: " + to_string(result));

} else {

logMessage("Error: Division by zero!");

return 0;

Follow the steps below to compile and run this program in Dev C++:

1. **Open Dev C++:**

- Open Dev C++ and load your C++ project.

2. **Compile the Program:**

- Ensure that you are compiling the program with debugging information enabled.

3. **Run the Program:**

- Run the program from the Dev C++ environment.

4. **Check the Log File:**

- Open the `logfile.txt` and check for log messages.

The log file might look like this:

Attempting division...

Error: Division by zero!

By following these steps, you can implement logging in a C++ program using Dev C++, allowing you to
analyze log output to identify and fix issues.

Task:

Complete the following table:

Error Program Error Type Identify Error Debugging Corrected Program


technique
#include
<iostream>
int main() {
cout << "Hello,
world!" << endl
return 0;
}
#include
<iostream>
int main() {
int x = 5;
int y = 0;
int result = x /
y; // Division by
zero
cout << "Result:
" << result <<
endl;
return 0;
}
#include
<iostream>
int main() {
int x = 5;
int y = 3;
int result = x *
y; // Incorrect
multiplication
cout << "Result:
" << result <<
endl;
return 0;
}

You might also like