← The C Language Lesson 56 of 77 · 10 XP

Debugging

Theory and problem statement

Machine translation, not yet reviewed by a native speaker.

Debugging is looking for the reason why a program does the wrong thing. The main techniques:

1. Debug printing. The simplest and most common way is to print intermediate values:

fprintf(stderr, "DEBUG i=%d sum=%d\n", i, sum);

Print to stderr, not to stdout: that way the debugging output won't mix with the program's real output.

2. assert statements. A check that must be true. If it isn't, the program stops and shows the file and the line:

#include <assert.h>
assert(n > 0);
assert(p != NULL);

3. The gdb debugger. It lets you stop the program at any line and look at the variables:

gcc -g main.c -o main      # -g adds debugging information
gdb ./main
(gdb) break main           # a breakpoint
(gdb) run
(gdb) next                 # the next line
(gdb) print sum            # the value of a variable
(gdb) backtrace            # where we are and how we got here (priceless after a crash)

4. Sanitizers. gcc -g -fsanitize=address,undefined main.c — the program itself tells you where it went out of an array's bounds or overflowed an int.

The main principle of debugging is to narrow down the place. Find the smallest input on which the error shows up, and the earliest line after which the values are already wrong.

Task. The program should print how many numbers from the input lie in the range from 10 to 20 inclusive, but it gives the wrong answer. Find the logic error. Tip: add debug printing to stderr — the check ignores it.

Sign up for free to solve this task right in your browser: code editor, running, test checks and hints.