logo
search-iconinfo-icon

GDB - Debug with core files

A Core Dump is a file containing a process's address space (memory) when the process terminates unexpectedly. This file is very useful for debugging, for example, segmentation faults.

Generate a Core Dump file

Most systems by default have the core dump file generation disabled. We can check by running the following command:

$ ulimit -c
0

To enable the creation we need to run the following commands:

$ ulimit -c unlimited

The program

To examplify how you can use the Core Dump and the GDB to better debug your programs, we will use this very simple program:

int main() {
        char* s = 0;
        char c = s[0];
        return 0;
}

Now we can compile and run the program.

$ gcc -g example.c
$ ./a.out
Segmentation fault (core dumped)

Make sure that the Core Dump file was created, you can use the "ls" command.

Debug

Now that we have the core file we can start the debug process.

Open GDB

$ gdb a.out core
Core Dump was generated by `./a.out'.
Program terminated with signal SIGSEGV, Segmentation fault.
#0  0x0000563a5b9f160a in nullPtr () at hello.c:3
3               char c = s[0];

The first thing we are going to do is use the "backtrace" command. A program when running maintains a call stack that contains information about the functions that have been called so far. Each item in the stack is a call frame, and each frame contains both the information needed to return to its caller and the information needed to provide the local variables of the function. Backtrace is used to get a stack trace from the time when the SIGSEGV was raised. Each frame in the stack has a number, where 0 is the most recent call.

(gdb) bt
#0  0x0000563a5b9f160a in nullPtr () at hello.c:3
#1  0x0000563a5b9f1621 in main () at hello.c:7

This example is trivial, but in normal cases, this backtrace is essential and gives the programmer a good idea of what the problem might be.

In some cases it might be useful to use the "frame" command to gives us more information about each frame. For example the frame 0:

(gdb) frame 0
#0  0x0000563a5b9f160a in nullPtr () at hello.c:3
3               char c = s[0];

This information is the same given by the debugger when we started. This is because the operation "s[0]" is trying to access an invalid memory position (0x0), which is the problem with our program.

edit-iconEdit this page