Tuesday, May 29, 2012

A list of things to remember when debugging a C program

These go for C++ as well. Assuming gcc/g++ and gdb.
  • Compile with -Wall and pay attention to warnings.
  • Turn off compiler optimization. Remove -O from your CFLAGS.
  • Turn on debugging. Add -g to your CFLAGS.
  • Set appropriate breakpoints.
  • There is nothing wrong with throwing in a printf statement to narrow down your search. Use fprintf to print to stderr.
  • gdb --args ./program --program-args
  • break filename:lineno
  • Use valgrind to eliminate memory leaks and clean things up. If you can't trigger it while debugging, it's probably a memory bug. (valgrind --leak-check=full -v --log-file=vg.out ./program --program-args)
  • Define the error condition, then determine how it got that way.
  • When you find the bug, look for similar bugs in all your other code.

No comments:

Post a Comment