Home | |
Schedule | |
Assignments | |
Lectures | |
Resources
Debugging
You are now writing programs that are interesting enough to contain subtle bugs. Here are some common ways to debug a
C++ program:
- Stare at it. This is probably what you have been doing up to now.
- Add print statements. Perhaps the most common way of debugging C++ programs, this sometimes works
surprisingly well. Just add cout statements at key points (or generously!) throughout your program. Inside a
conditional, you might insert:
cout << "I'm now inside the TRUE part of the conditional\n";
Inside your LookupCode function you might put this near the start:
cout << "LookupCode was called with target " << target << endl;
and near each return statement put:
cout << "LookupCode is about to return character " << letter << endl;
The result is that when you run your program, you get a nice printout showing how conditionals were executed, which
functions were called, the value of important parameters and variables, etc.
- Test it. Run your code with many different inputs to watch how it behaves. With good planning and a little
luck, knowing which inputs work and which inputs don't work can help lead you to the bug.
- Use a debugger like GDB. Hard to learn and easy to forget, but this method gives you the most information
about what is happening inside your program.
GDB Cheat Sheet
Starting GDB. From within emacs, select GDB from the menu, then append the name of your compiled program at
the bottom. If your program is called hello, it should read:
Starting GDB from the command line. From within the directory where your program is stored, run the same command as above.
Set a breakpoint.
- break main - stop when we get to main.
- break MyFunction - stop when we get to MyFunction.
- break 23 - stop when we get to line 23.
Start the program.
Resuming after hitting a breakpoint.
- next - continue forward to the next line of code.
- step - similar, but steps into function calls too.
- continue - start running again.
- run - start over from the beginning.
Getting information after hitting a breakpoint.
- where - show where in the source code the program is.
- list - show a few lines of source code (useful when outside of emacs).
- print myVariable - show contents of myVariable.
- display myVariable - same, but show it whenever we stop.
Home | |
Schedule | |
Assignments | |
Lectures | |
Resources
|