Physics and Astronomy |
Back to top
On this page
Contents Exercise: using the debuggerWe present this in three main levels: basic, intermediate and advanced. As always the 80/20 rule applies and the "basic" steps of examining the state of a crashed program, or seeing why a program seems to be sitting there doing nothing at all, are by far the most useful. Try the intermediate level as well as it's quite easy, and if you're really keen try the semi-advanced and advanced material as well. But it's the basic stuff that is by far the most important, so be sure to do at least that. Basic: debugging crashed programsThis is our most important single use of the debugger. At this stage crashed programs are usually the result of going over the end of an array or giving bad arguments to scannf(), so we shall proactice both in turn. (We shall later find other ways to crash programs but the principle of debugging them is the same.) Exercise: going over the end of an array1. Create the buggy programCreate a new project and paste the following into main.c: Notice the error in the for() loop where we have written "one is less than N" rather than "i is less than N". 2. Run the programIt will crash horribly. Essentially we are now in the situation we will often find ourselves in: our program crashes and we need to know why.
3. Check the "Call stack" and "Watches" windows are enabledRunning under the debugger 4. Run under the debuggerNow from the Debug menu choose
Start.
4. Observe what happens when the program crashed5. Play around!Switch to frame menu One of the most interesting things to do is to right-click
on the word main() in the Call Stack window
and select "Switch to this Frame".
The window will now look like this: The window now shows where within main() the function badfun() was called from along with the values of the local variables within main(). One interesting thing to notice is the variable j. This has had its value changed to "100". This is the sort of behaviour we expect when we go over the end of an array: "innocent" variables have their values randomly changed. (NB: the effect may be different when you try t, by definition the results tend to be unpredictable.) Try clicking on the triangle to the left of myarray in the
top right pane. You should see a list
of its individual elements.
(Unfortunately this only works in the function
where the array was originally defined, because sub-functions
do not know where the array ends.)
Exercise: a bad call to scanf()Programs can also crash due to bad calls to scanf(), although as always the compiler will usually warn us. Close all your windows, create a new project and paste this particularly hideous example into main(): #include <stdio.h> // Deliberately make scanf() crash int main (void) { scanf("%lg", (double *) 45378344); // !!!! return 0; } Here we are trying to read a double into a pretty random location in memory (byte number 45378344!). Log in |