Wednesday 27 March 2013

Popular C program crashes, Reasons and how to detect them
Crash:    Segmentation Fault

Reason:  Segmentation Fault is occurred when program tries to access(write or read) memory not owned by program itself
      Ex.,
       /* Program name segfault.c */
       #include <stdio.h>
       int main()
       {
            int *a=NULL;
            *a = -1; /* results in segmentation fault*/
            return 0; 
       }

Detection:  In Linux, compile the program with debugging enabled. Means you  have to compile the program with -g option
           
user@syam:~/crashes$gcc -g segfault.c -o segfault  
user@syam:~/crashes$gdb segfault
GNU gdb (Ubuntu/Linaro 7.4-2012.04-0ubuntu2.1) 7.4-2012.04
Copyright (C) 2012 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>
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 "i686-linux-gnu".
For bug reporting instructions, please see:
<http://bugs.launchpad.net/gdb-linaro/>...
Reading symbols from user@syam:~/crashes/segfault...done.
(gdb) r
Starting program: user@syam:~/crashes/segfault

Program received signal SIGSEGV, Segmentation fault.
0x080483c4 in main () at segfault.c:5
5      *a = -1; /* results in segmentation fault*/
(gdb) bt
#0  0x080483c4 in main () at segfault.c:5


gdb command bt shows backtrace where crash is occurred i.e at line number of segfault.c file

No comments:

Post a Comment