Sunday 10 March 2019

Segmentation Fault -- Common Scenarios


As we all know that Segmentation fault is condition which led to program crash and this crash is mostly associated with  program reading or writing on some illegal memory. No this post is not about the theory of segmentation fault but it is about scenarios which can lead to program crash.

To start with let's take first example where we are trying to write to a read only memory which ultimately crashed the program.

/*This constant string will be stored in read only memory but c++ allows 
non-const pointer to point to it */
char *name="Kapil Vermani";
/*This will led to segmentation fault (with gcc compiler) as 
you are trying to change read only memory*/ 
name[0] = 'P'; 
//Below line will never be printed
std::cout<<"Name is now "<<name<<std::endl; 

Another straightforward example could be trying to dereference a null pointer which in most cases lead to segmentation fault because you are accessing memory which is not mapped but sometime also led to access violation.

int fact(int n)
{
 char *ptr = nullptr;
 std::cout<<"value of ptr is "<<*ptr<<std::endl;
 return 0;
}

One example that i encounter today while working on stackoverflow question is related to recursion so whenever you have written a recursive function you have to specify exit condition otherwise your program will terminate with segmentation fault. An example for this is as follows :

int fact(int n)
{
  return n*fact(n-1);
}
int main()
{
fact(2);
return 0;
}

Above example will create segmentation fault as there is no exit condition so function calls will go like fact(2)-->fact(1)-->fact(0)-->fact(-1) ...... unending which will lead to stack overflow and hence seg fault.

I will add more examples when i encounter other segmentation fault scenarios.
Thanks for reading!

No comments:

Post a Comment