Wednesday, November 6, 2013

Quick tutorial: Debug segmentation faults with GDB

1. When you see a segmentation fault (segfault), the first thing you need to debug it is the ability to generate a core file. What is a core file? A core file is an image of a process that has crashed It contains all process information pertinent to debugging: contents of hardware registers, process status, and process data. Gdb will allow you use this file to determine where your program crashed. To ensure that you can generate a core, run the following command (if you are using bash):
ulimit -c unlimited
if using (tcsh):
limit coredumpsize unlimited
2. Once this is done, run the program again (which shows the segmentation fault). After the binary is run and it crashes, you should see a file with the name core.XXXX  in the same directory. Here XXXX is some number.

3. Read the core file using GDB. All you need to do now is run GDB with the program and the core file as gdb program core. So an example would be as shown below:
gdb path/to/the/binary path/to/the/core

4. Finally you can run the GDB backtrace command (bt) in the GDB shell to see the exact location where the program crashed. In the backtrace, each function call is assigned a  different number. These frame numbers can be used to select a particular stack frame. You can then use list to see code around that function, and info locals to see the local variables. You can also use print name_of_variable (replacing "name_of_variable" with a variable name) to see its value.






0 comments:

Post a Comment