CS253

This file defines the header for each page. An optional "icon" image (I use the textbook):

Replace this with info about this class:

CS253: Problem Solving with C++

Spring 2013

Debugging Lab

Links to the various pages for this class:

Wish I could do this: * Schedule

Debugging

In this lab, you will learn to use debugging tools such as gdb, assert, and -D_GLIBCXX_DEBUG.

Consider the following program, bad.cc. It opens resolv.conf, and prints out the line that starts with “search”. It has several errors (don’t rob others of the joy of discovery—keep it to yourself):

#include <fstream>
#include <iostream> 
#include <string>
#include <cassert>

using namespace std;

int main() {
    string filename = "\etc\resolv.conf";
    // A stupid line just to introduce an error:
    cout << "The 3rd character is " << filename[100000003] << '\n';

    ifstream in(filename.c_str());
    assert(in.is_open());

    string s;
    while (getline(in, s)) {
        string prefix = s.substr(1,6);
        if (prefix == "search")
            cout << s << '\n';
    }

    return 0;
}

When the program works, it prints something like this:

    search cs.colostate.edu colostate.edu

For this lab, you should:

  1. Copy & paste the program to bad.cc.
  2. Compile it, like this: g++ bad.cc
  3. Execute it, observe the segmentation fault, obviously caused by filename[100000003]
  4. Compile it, with the C++ library debugging flag, like this: g++ -D_GLIBCXX_DEBUG bad.cc
  5. Execute it, observe the more helpful error message. It’s not perfect, but it beats “Segmentation fault”.
  6. Fix the offending line by changing [100000003] to [3].
  7. Compile & execute, see the assert failure.
  8. Compile it, like this: g++ -DNDEBUG bad.cc
  9. Execute it, observe that the assertion failure vanished (and the program still doesn’t work).
  10. Compile for the debugger gdb: g++ -ggdb bad.cc
  11. Execute the debugger: gdb ./a.out
  12. Set a breakpoint at the assertion: b 14 (your line number may vary)
  13. Run the program: r
  14. Print the value of filename, like this: p filename.c_str()
  15. Figure out why filename has that value. Fix the source.
  16. Recompile for the debugger.
  17. Set a breakpoint at if (prefix == "search") line.
  18. Run the program to that breakpoint, inspect s and prefix the same way that you printed the value of filename.
  19. Fix the call to «string::substr(cpp)».
  20. Recompile, see that the program works correctly.

For extra fame & glory:

  1. Debug the program using ddd.

Modified: 2013-01-31T17:32

User: Guest

Check: HTML CSS
Edit History Source
Apply to CSU | Contact CSU | Disclaimer | Equal Opportunity
Colorado State University, Fort Collins, CO 80523 USA
© 2015 Colorado State University
CS Building