Debugging Techniques
Use of Simple Print Statements
Okay, the program compiles, but it does not work as
planned or even worse it is crashing, and there is no clue why. One of
the most elementary debugging techniques is to place print statements in
the source code.
The following example, although very simple, illustrates the use of this
debugging method...
Source Code Before:
#include <stdio.h>
int main()
{
int array[10];
int i;
for (i = 0 ; i < 20 ; i++)
{
array[i]=1;
}
for (i = 0; i < 10 ; i++)
{
printf("%d", array[i]);
}
return 0;
}
|
|
Compilation & Execution Before:
linux1[30]% gcc -ansi -Wall main.c
linux1[31]% a.out
Segmentation fault (core dumped)
linux1[32]%
|
In the above example the code compilied okay, no errors. At run time
the program attempts to index out of the array. It crashes and no insight
as to what went wrong is present.
|
Source Code After:
#include <stdio.h>
int main()
{
int array[10];
int i;
for (i = 0; i < 20 ; i++)
{
printf("In for loop: i = %d\n", i);
array[i]=1;
}
for (i = 0; i < 10 ; i++)
{
printf("%d", array[i]);
}
}
|
|
Compilation & Execution After:
linux1[33]% gcc -ansi -Wall main.c
linux1[34]% a.out
In for loop: i = 0
In for loop: i = 1
In for loop: i = 2
In for loop: i = 3
In for loop: i = 4
In for loop: i = 5
In for loop: i = 6
In for loop: i = 7
In for loop: i = 8
In for loop: i = 9
In for loop: i = 10
In for loop: i = 11
In for loop: i = 12
In for loop: i = 13
In for loop: i = 14
In for loop: i = 15
In for loop: i = 16
In for loop: i = 17
In for loop: i = 18
In for loop: i = 19
Segmentation fault (core dumped)
|
With the print statements in, it can be seen that the "for
loop" was executed 15 times. It can be seen that an extra 10 print
statements occurred, whereas in the source code there is only 1, less
visible error that may be overlooked.
|
Notes:
- Use meaningful print statements
- Do not use statements such as "1", "here" or
"here2" as they will need to be searched for in the source
code
If in a function state so... "InFoo()"
Print out variable names and values... "i = ?, x = ?"
- Do not forget the newline character
- "printf("InFoo()");" will not print anything
to
the screen
"printf("InFoo()\n");" will print to the screen
(The output buffer needs to be flushed, and this is a
way in which that happens)
- Leave the print statements at the left margin
- All of the prints will need to be removed anyway, so make it easier to
spot them. If the are
indented, they might be hard to spot and remove.
Modified by:
Dawn Block,
September 2003
Created by:
Daniel J.
Hood,
February 2000 http://www.csee.umbc.edu/~cshc/resources/debug/prints.shtml
|
|
|