Noeud:A Program With Bugs, Noeud « Next »:, Noeud « Up »:How to Use a Debugger



A Program With Bugs

This is the example program we'll be using to demonstrate how you would typically use gdb to track down bugs. It has a number of bugs, some obvious, some not so obvious. It compiles with no warnings using 'gcc -g ecount1.c -o ecount1'

The program has a simple task to perform - it takes one parameter, a single word, and counts the number of letter 'e's in it. It prints the result to the screen. That shouldn't be too difficult, should it?

     /*
      * ecount1.c	Simple program to count the number of letter 'e's that
      *		appear in the word given as the only parameter
      *
      *		WARNING: This program contains several deliberate bugs
      *			 (and possibly some others...)
      */
     
     #include <stdio.h>
     
     int main( int argc, char *argv[] )
     {
       char *buf=NULL;
       int count, i;
     
       /* check we have a parameter */
     
       if( argc = 1 )
       {
         printf( "Usage: ecount <word>\n");
         exit(1);
       }
     
       /* Make our own local copy of argv[1] */
     
       strcpy( buf, argv[1] );
     
       /* print it out to show we received it correctly
     
       printf( "The word is '%s'\n", buf );
     
       /* Now step through counting letter 'e's */
     
       for( i=0; i<strlen(buf); ++i )
       {
         if( buf[i] == 'e' ) ++count;
       }
     
       return(0);
     }