August 08, 2008

Linux C Code Debugging for Segmentation Fault with GDB

Hi Friends,

Whenever you are doing some programming, you will be getting lot of errors. Myself have been in the same situation while programming.

When I was tried to write a code in C language (though I'm not a good programmer of C language), For my friend's sake I have tried some code.

The most frustrating error came in to picture, called "Segmentation Fault". Took help of google and no clue why I was getting the error.

What I have understand about Segmentation fault is
"Segmentation fault appears as if it is not easy to understand;
when your trying to access the memory that is not allocated by you ...
then segmentation fault appears after executing a.out"

Let me explain you with an example

int a[5]; // Declare an array
printf("%d\n",a[6]); // Then try to print the last+n location of the array where n>0

You will get segmentation fault error.


How to over come this?

There are different debuggers to locate the memory area where the segmentation fault occurred.

Procedure:
  1. 1.c // Your file name
  2. gcc 1.c -g // Then compile it
  3. gdb a.out // Type at the command prompt/console
  4. Now you will get a prompt >>>
  5. Type 'r'
  6. Give the required input
  7. It will locate the memory area where your trying to access the memory
  8. u is not allocate by u (it will give the lines in the program 1.c here segmentation fault has occurred )

You can rely on gdb about 70% and there are also other debuggers
for which you can refer to the book "Linux is a Nutshell"

For further queries/comments mail to psrdotcom@gmail.com
Post a Comment

Featured Post

Java Introdcution

Please send your review and feedback to psrdotcom@gmail.com