Debugging C++ with GDB

An example…

If you want to know how to launch GDB, then an example program with GDB commands are provided at the bottom of this page, click here to go to them.

How do I tell where I am at while debugging?

GDB let’s you move up and down the stack, so you must first understand the difference between:

  1. Where has the program stopped for debugging?
  2. Where in the stack am I currently at?

Where has the program stopped for debugging?

To see where you are in the program (print a stack back-trace):

where
info stack
bt

To see the file and location of at the top of the stack (where the program stopped):

frame 0

To see the code at this location run:

list

Just remember, that if you run list again, it will continue down the file – run ‘frame’ again to reset it.

Where in the stack am I currently at?

To see the file and location of where GDB is in the stack:

frame

If you want to see registers and frame arguments run:

info frame

You can move up and down the stack with:

up
down

To see the code around where you are:

list

What source file is this symbol defined in?

If you are in GDB and need to see what file a symbol is defined in, then run:

info types <type>

You can also just print them all with:

info types

How do I invoke code?

Just print it:

p myShapePtr.getSize()

Catch any Throw

If your program is crashing and you just want to see why, then you can tell GDB to catch a throw using a catchpoint. To create such a catchpoint use:

catch throw

This will catch every throw your program does.  What you may be surprised to find is that some libraries throw and catch and you may find yourself in unexpected locations hitting catchpoints that threw.

You can do much more with the catch command, you can tell it to set a catchpoint at any of these:

throw - The throwing of a C++ exception.
catch - The catching of a C++ exception.
exec - A call to exec. This is currently only available for HP-UX.
fork - A call to fork. This is currently only available for HP-UX.
vfork - A call to vfork. This is currently only available for HP-UX.
load || load libname - The dynamic loading of any shared library, or the loading of the library libname. This is currently only available for HP-UX.
unload || unload libname - The unloading of any dynamically loaded shared library, or the unloading of the library libname. This is currently only available for HP-UX.

 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s