Sunday, February 26, 2006

What is Segmentation Fault

What is Segmentation Fault? This is the question that i was asked by many students when i am taking Data Structures Lab. A Segmentation fault occurs when your program is accessing a memory location that is not allowed to access.
A simple Example is
...
scanf("%d",i);
....
here i forgotten to insert '&' before i, and when i tried to run this program, and if i value entered is 100, the compiler is going to access the memory location '100', which is not accessible by our program. Since in the scanf() we must pass the address of the variable to store the value.

Another situation occurs when we are trying access index of an array which is out of its range.
say, if
...
int a[20],i;
...
i=30;
a[i]=50;
....
here, a, is an array of size 20, and some location a[30] is about to access(write), so its giving segmentation fault.

It may also exist when we freed some memory location and are trying to access the same location after some time, which means that we are about to access a memory location which is non-existing.

So collectively, in the view of operating systems concepts, a segmentation fault occurs when we are trying to either read or write non-existing segment (a block of physical memory), which may crash ur system.

One way to find out where the error is occuring is using debugger. Its better to use coredump { the CORE(RAM memory) contents are copied into some location, when a process is aborted.}, and try in gdb to locate the error.

No comments:

Post a Comment

Drop your message here to get in touch with me