Wednesday, January 15, 2014

Find the line where segmentation fault occurs


With using gcc, new users generally gets a segmentation fault while doing operations with pointers in C. As gcc is the most robust compiler of C, it doesn't allow to do anything wrong with memory references. Your TurboC++ compiler may allow invalid memory references in many cases but gcc may not. But, don't be scared of it. By using one of the best debuggers 'gdb' will find the line where core dump- segmentation fault occurs.


There are six reasons for occurrences of segmentation fault in C program. Out of all, generation of SIGSEGV is most frequent event which leads segmentation fault. Consider following example:

    #include<stdio.h>
    int main()
    {
       int x,*y,*z;
       x=10;
       *y=12;
       *z=x+*y;

       printf(”Addition is %d”,*z);
       return(0);
    }

This program will work fine in TurboC++ compiler but gcc will produce segmentation fault. As, it is a run time error the line where return fault has occurred, won't be displayed. So, what to do..?
Let see find it. First compile the program as,

gcc myprogram.c -g

The program will be compiled successfully and it will generate a.out file which is executable. We may use -o option also to give another name to output file. The -g option here gives ability to output file to get debugged. Now, the debugger will be enabled for output file a.out . Use gdb (GNU debugger) to debug program.

gdb a.out

This will start debugging and gdb> prompt will be shown. Use 'break' instruction to insert breakpoint in the program. Such as,

gdb> break 1

It will insert breakpoint at line no.1 in the program. Now, run the program by 'run' command.

gdb> run

This will execute your program till first breakpoint then after, we may step through our program by 'next' command. The 'next' command will execute the program line by line.
Wherever you find the segmentation fault, the program will stop on that line it will also show the line number. The above program will stop the execution due to segmentation fault on line no.6. It is invalid memory reference which is not allowed by gcc!