CS253

CS253: Software Development with C++

Fall 2010

Debugging Lab

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 the list of filesystems, and prints out the line that starts with “proc”. It has several errors (don’t rob others of the joy of discovery—keep it to yourself):

(:source lang=cpp filename=bad.cc -inline:)

  1. include <fstream>
  2. include <iostream>
  3. include <string>
  4. include <cassert>

using namespace std;

int main() {

    string filename = "\etc\fstab";
    // 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,4);
        if (prefix == "proc") {
            cout << s << '\n';
        }
    }

    return 0;

} (:sourceend:)

When the program works, it prints something like this:

    proc                    /proc                   proc    defaults        0 0

For this lab, you should:

  1. Copy & paste (or download) 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 15 (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 == "proc") 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‡.
  20. Recompile, see that the program works correctly.

For extra fame & glory:

  1. Debug the program using ddd.

Modified: 2009-01-31T21:33

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