Noeud:Moving Around the Call Stack - Up+Down, Noeud « Next »:, Noeud « Previous »:Finding Out Where You Are - Backtrace, Noeud « Up »:An example debugging session using gdb



Moving Around the Call Stack - Up+Down

We now have just enough information to find the line which caused the segmentation fault, but it would be nice to have gdb sat on that line so we can use the source listing and variable prnting commands to find out why it happened.

gdb will only allow you to examine variables which are in scope at the place where it is, so we cannot examine local variables of main() from inside strcpy.

The answer to this is the up and down commands. As the names suggest, up moves one step up te call stack, to #1 main(), while down moves down one step. We can't go down from here as we are already at the lowest level, so let's try up

     (gdb) up
     #1  0x80484d5 in main (argc=2, argv=0xbffff964) at ecount2.c:26
     26	  strcpy( buf, argv[1] );
     (gdb) list
     21	    exit(1);
     22	  }
     23
     24	  /* Make our own local copy of argv[1] */
     25
     26	  strcpy( buf, argv[1] );
     27
     28	  /* print it out to show we received it correctly
     29
     30	  printf( "The word is '%s'\n", buf );
     

Now we are back in the situation we were in before, at line 26 in main.c. We can examine all the variables and list the source. Note that we can't use the step and next commands from here because we don't actually have a running program to step through, only an image of the state it was in when it crashed.

We can now see that the first argument to strcpy was the variable buf, so let's look at what has been done to that. In a comlex program, we would use an editor or even a class browser to do this, but here we know it is defined at the top of main, so let's have a look there.

     (gdb) list main
     8
     9	#include <stdio.h>
     10
     11	int main( int argc, char *argv[] )
     12	{
     13	  char *buf=NULL;
     14	  int count, i;
     15
     16	  /* check we have a parameter */
     17
     (gdb)
     

So buf was initialised to NULL, and no memory was ever allocated to it. I think we have found our bug. Let's fix it and try again with ecount3.c.