UMBC CMSC 201 Spring '05 CSEE | 201 | 201 S'05 | lectures | news | resources |discussion| help

OK, It Compiles, Now What?

You know by now that getting your code to compile is less than half the battle. If your program is acting funny, there are a few things you can do.

One is to use probes -- simple printf statements inserted to print useful information about the state of your program as it runs.

Probes - printf() statements

Lots and lots of printf() statements. Print out every variable you pass in to a function every variable that changes, and every variable that comes out. Print out your constants, and the result of every computation. Then when you run your program, look at all the values of all the variables and see if you can figure out what's going wrong.

Statements like

  • In MyCoolSortFn(), at the top, a=5
  • In main, after MyCoolSortFn(), counter = 12
create a much clearer picture of what's going on than
  • here
  • here2
  • #1
  • b

Because output to stdout is buffered, printf() statements must contain a newline character or they will not always give you an accurate picture of your program execution if the program stops suddenly, as in a segmentation fault or bus error.

Conditional probes

I'm sure you've experienced this:
  • You've got bugs in your program, so you add a bunch of problesm
  • You found your bugs and fixed them
  • So you delete the probes
  • Only to have to put them back when your further work introduces new bugs

(1) One solution is to comment out the probes and only delete them when you freeze the code.

(2) Another solution is to put the probes inside a condition, e.g.:

#define DBUG 1
...
void foo (int x, int y) {
   if (DEBUG) {
      printf{"Calling foo(%d,%d)\n", x, y);
	}
   ...
}
If you *think* your code is ok, you can define DBUG to be 0.

(3) A third approach is to use C's conditional compilation facility.


CSEE | 201 | 201 S'05 | lectures | news | resources | help |

Monday, 18-Apr-2005 13:43:11 EDT