How to debug C programs. Practical coverage of printf debugging and common bugs.
filename:line:col: error: message. The trick is to fix the first error first.;. Check the line before the one reported.int x = 10 // ← no ; ! printf("%d", x);
#include.%d where a double needs %f.printf to trace program behavior. Beginners can use it immediately.// Technique 1: print variable values printf("DEBUG: x=%d, y=%d\n", x, y); // Technique 2: check if execution reached this point printf("DEBUG: reached before loop\n"); // Technique 3: print loop variables every iteration for (int i = 0; i < n; i++) { printf("DEBUG: i=%d, sum=%d\n", i, sum); sum += a[i]; } // Technique 4: see which branch was taken if (x > 0) { printf("DEBUG: x is positive\n"); } else { printf("DEBUG: x is 0 or negative\n"); }
i start from? Does a[5] exist?i=1 instead of i=0, or used i<=n instead of i<n, etc.// NG: accesses a[5] (out of bounds) for (int i = 0; i <= 5; i++) sum += a[i]; // OK: for (int i = 0; i < 5; i++) sum += a[i];
int sum; // ← initial value is garbage! for (...) sum += a[i]; // garbage + a[i] = ? // Correct: int sum = 0;
if (x = 5) assigns 5 to x (always true). Use == for comparison.if (x = 5) // NG: assigns 5 to x (always true) if (x == 5) // OK: checks whether x equals 5
int i = 0; while (i < 10) { printf("%d\n", i); // forgot i++! -> i stays 0 forever }
scanf("%d", &x), not scanf("%d", x). Without the address scanf crashes.scanf("%d", x); // NG: crash! scanf("%d", &x); // OK
average = 5.00.Check your understanding!
By printing variable values or the execution path with printf, you can locate the cause of a bug. It is the most basic debugging technique.
Debuggers support setting breakpoints, stepping, and watching variables — all the tools needed for detailed program analysis.
Writing a little and testing often lets you locate bugs quickly. Comments also matter.