Wednesday, 12 August 2015

How to use gdb tool to generate core file caused by Segmentation fault

How to use gdb tool to generate core file caused by Segmentation fault :

First of all we need to know about what is segmentation fault? When the segmentation fault will occur?

A program that is trying to access unauthorized memory location caused the segmentation fault.
The segmentation faults occurred by different reasons as shown below.

Improper use of pointers in the source code, let us see the sample code.

Here is the file to generate the core file. The code is dereferencing a NULL pointer in SegFaultTest (), and when we run, it gives us core file.

int SegFaultTest (int *MyPtr)

     int iVal = *MyPtr;
     return iVal;
   int main ()
     int *ipVal = 0;   /* null pointer */
     return SegFaultTest (ipVal);

Compile and run the above program
$ gcc -g -o ./ SegFaultTest SegFaultTest.c

$ ./ SegFaultTest

Segmentation fault

$ ls

SegFaultTest SegFaultTest.c

As we know all that signal SIGSEGV set, that is defined in the header file signal.h file.When the program receives the SIGSEGV then that program gets terminated abnormally. It may generate the core file with the history where the problem occurred. That is also called as core dump.

A core dump is there corded state of the working memory of a computer program at a specific time, generally when the program has terminated abnormally.

In the above compile and running process we can observe that the core was not made. To generate the core file, we need to do specify the size of the file:
$ ulimit -c


$ ulimit -c unlimited

$ ulimit -c


SegFaultTest SegFaultTest.c

Run the program again:
$ ./SegFaultTest

Segmentation fault (core dumped)

$ ls

SegFaultTest   SegFaultTest.c  core.2333

Now, let's run gdb with the exec and core file names as arguments:
$ gdb ./SegFaultTest  core.2333

GNU gdb (GDB) Fedora (7.5.1-37.fc18)

Copyright (C) 2012 Free Software Foundation, Inc.

License GPLv3+: GNU GPL version 3 or later

This is free software: you are free to change and redistribute it.

There is NO WARRANTY, to the extent permitted by law.  Type "show copying"

and "show warranty" for details.

This GDB was configured as "x86_64-redhat-linux-gnu".

For bug reporting instructions, please see:


Reading symbols from /home/…/…/…/Debug/SegFaultTest ...done.

[New LWP 2333]

Core was generated by `./SegFaultTest '.

Program terminated with signal 11, Segmentation fault.

#0  0x00000000004004f8 in SegFaultTest  (pt=0x0) at SegFaultTest.c:5

5   int x = *pt;

(gdb) backtrace

#0  0x00000000004004f8 in SegFaultTest  (pt=0x0) at SegFaultTest.c:5

#1  0x000000000040051e in main () at SegFaultTest.c:12


No comments: