Debug-And-Core-Dump

GDB debugging

To debug, we can use gdb. Given that gdb program is installed.

We can use:

g++ -g main.cpp -o main

The -g will include debug symbol for debug options

gdb main

In gdb, we can use command such as:

  • where to find the current cursor location
  • list (l) to list the lines
  • b 50 to set a breakpoint at line 50
  • step to step into a function

...

Core file

Sometimes when segmentation fault happens, a core file will be generated.

First, we can read how much memory core-dump can use by using

ulimit -c

If this returns 0, it means that core-dump is not allowed to use. To enable core-dump, we can do

ulimit -c unlimited

This will set the maximum memory to be unlimited, so that we can use core-dump.

In Ubuntu, apport will handle the core dump. To find out where this core file is generated, do

cat /var/log/apport.log

This should have some logs where this file was saved. Afterwards, we can analyse the file like

gdb main /path/to/core/file

This will break right at the point where the segmentation core was thrown.

Keep symbol file separately

We can compile and extract the debug symbols out. And then keep the symbol file separately.
This wil add security to our code base that whoever has the executable file cannot just debug.

  1. Compile the program with debug option -g
g++ -g main.cpp
  1. Extract the debug symbol to a separate file
objcopy --only-keep-debug main main.debug
  1. Strip the debug symbol from main
strip --strip-debug --strip-unneeded main
  1. Load the main program and debug program separately
$ gdb main
(gdb) symbol-file main.debug
(gdb) # Now we can debug