Chapter 37 of 37

Debugging

While writing programs, it's normal to make mistakes. Sometimes the program doesn't compile, sometimes it crashes, and sometimes it runs but produces the wrong result.

Finding and fixing these problems is called debugging.

What is Debugging?

Debugging is the process of finding, understanding, and fixing errors or bugs in a program.

A bug is an error in a program that causes it to behave incorrectly.

For example:

int a = 10;
int b = 20;

printf("%d", a - b);

If we wanted to calculate the sum, the program runs successfully but gives the wrong result. This is a logical error.


Common Types of Errors

1. Syntax Errors

These happen when we don't follow C's syntax rules.

int age = 20

The semicolon is missing, so the compiler reports an error.

2. Runtime Errors

These happen while the program is running.

For example, attempting an invalid memory access can cause a crash.

3. Logical Errors

The program runs successfully but produces the wrong output.

int result = 10 - 5;

If we actually wanted addition, the program's logic is incorrect.


How to Debug a C Program

A simple debugging process is:

Find the problem
      ↓
Understand the cause
      ↓
Fix the code
      ↓
Run the program again
      ↓
Test the result

You can use several techniques to find bugs.

1. Read Error Messages

Compiler and debugger messages often tell you where a problem occurred.

2. Use printf()

Printing values can help you understand what your program is actually doing.

printf("value = %d\n", value);

3. Use a Debugger

Tools such as debuggers allow you to:

  • Set breakpoints

  • Execute code step by step

  • Inspect variable values

  • Watch how the program changes during execution

4. Test Different Inputs

Don't test your program with only one input. Try normal, boundary, and unexpected inputs.

In Simple Words

Debugging means finding and fixing bugs in a program.

Remember:

Syntax error → Code doesn't follow C syntax

Runtime error → Problem occurs while running

Logical error → Program runs but gives the wrong result

Debugging is a normal part of programming. Even experienced programmers encounter bugs—the important skill is knowing how to systematically find and fix them.