Debugging practice using lab3 sample solution

Today we'll take a quick look at using debuggers, particularly the gdb debugger, as a programming aid.

Some slides and videos are available here:

DEBUGGER EXERCISE:

This is just meant to try out the various debugger features (break, run, next, continue, print, backtrace, and quit).

Try the following using the posted lab3 sample solution (lab3.cpp)

  1. save the file above someplace in your csci159 directory (not in your lab3 directory, so you don't accidentally trash your own lab3 work)

  2. compile it into an executable using
    g++ -g lab3.cpp -o lab3x

  3. start the gdb debugger with your lab3x using
    gdb ./lab3x
    the command prompt will then show up as (gdb)

  4. run the following commands to set break points in the program
    break welcome
    break 91
    The first one makes the debugger pause for instructions when the welcome function is first called, while the second one makes it pause each time it hits line 91 (in the getCSize function, just before the user is asked to enter the size of a container).

  5. start the program running using the command
    run
    It should run until the program hits the welcome function, then will stop and wait for another debugging command.

  6. get the program to resume running using the command
    continue
    This time it should run until it first hits line 91. (In the meantime it will print out messages normally and ask you for the name of the container.)

  7. get the program to step through the next couple of instructions one line at a time, using the following command repeatedly
    next
    Keep going as it asks you to enter the size, type in foo as your response, and keep entering next until it displays the message about "Sorry, that was not a valid number".
    (Remember it will show you the line of code that prints the message first, then actually print the message after you enter next again.)

  8. try printing out the current container size and name using the following commands
    print containerName
    print contSize
    (It tracks variable and parameter names as $1, $2, etc, so don't be surprised by that when it displays the variable and value.)

  9. now let the program resume running normally until it hits line 91 again using continue
    continue

  10. get a list of the functions that are currently active using the following command
    backtrace
    It shows the current getCSize call on top, the previous getCSize call underneath, and the call to main on the bottom.

  11. use continue again, enter a valid value when asked, and enter continue one last time ... the program should run to completion.

  12. to exit the debugger use the command
    quit

I strongly encourage students to begin using debuggers on a regular basis to try to assess what is happening in their code when bugs arise.