C ยท Chapter 44 of 45

C Debugging Tips

Debugging is the process of finding and fixing errors in your code. Common C bugs include off-by-one errors in loops/arrays, uninitialized variables, mismatched printf/scanf specifiers, and pointer mistakes.

Tools like compiler warnings (-Wall), debuggers (gdb), and memory checkers (Valgrind) help catch problems that are easy to miss just by reading code.

Syntax
gcc -Wall -Wextra file.c -o file
gdb ./file
valgrind ./file

Use compiler warnings

Compiling with `gcc -Wall -Wextra` surfaces many potential bugs, like unused variables, mismatched types, and uninitialized values, before you even run the program.

Use a debugger and memory tools

gdb lets you step through code line by line, inspect variables and set breakpoints. Valgrind detects memory leaks and invalid memory accesses that are otherwise hard to spot.

Example 1 (bash)
gcc -Wall -Wextra buggy.c -o buggy
Output
buggy.c:5: warning: 'x' may be used uninitialized

Compiler warnings catch subtle bugs like uninitialized variables before runtime.

Example 2 (bash)
valgrind ./buggy
Output
== 12 == Invalid read of size 4

Valgrind detects invalid memory access, like reading past an array's bounds.

Key points

  • Always compile with -Wall -Wextra to catch potential bugs early.
  • gdb lets you step through code and inspect variable values interactively.
  • Valgrind helps find memory leaks and invalid memory accesses.
  • Printing variable values with printf is a simple but effective debugging technique.
๐Ÿ’ก Note: Treat every compiler warning seriously โ€” most 'weird' runtime bugs in C trace back to an ignored warning.

๐Ÿ“ Quick Quiz

1. What flag helps surface extra compiler warnings?

2. Which tool helps detect memory leaks?

3. What does gdb let you do?