What is segmentation fault?

When programming in c++ I often encounter segmentation fault.

What is it and how to debug it?

Regards,
Megh Parikh

When your program runs, it has access to certain portions of memory. First, you have local variables in each of your functions; these are stored in the stack. Second, you may have some memory, allocated during runtime (using either malloc, in C, or new, in C++), stored on the heap (you may also hear it called the “free store”).Your program is only allowed to touch memory that belongs to it – the memory previously mentioned. Any access outside that area will cause a segmentation fault. Segmentation faults are commonly referred to as segfaults.
It occur when you write -

 scanf("%d",n) 

But right code is

 scanf("%d",&n);

When you declare size of array is 10 and in main program you will use more than array size .

4 Likes

Looks like most of my errors are caused by local variables for I donot use any thing else. Do you know of any other reasons? I have a practoce of declaring each variable as global, so I think that there must be some other reason.(I encountered this error in last year codejam many times)

Segmentation fault occurs for various reasons.
Few are

  • Declaring local array or string which use large memory.
  • Stack Overflow generally due to large recursions
  • Dereferencing a pointer
  • Accessing a memory location not declared .

EX:- int arr[100],x=-1; cout<<arr[x];//segmentation error x=101; cout<<arr[i];//Segmentation error as program is trying to access memory out of bounds
Source: http://en.wikipedia.org/wiki/Segmentation_fault#Causes

1 Like

Thanks, now I understand the reason as sometimes I use excessive recursion. What is limit for recursion?

I think that depends on the memory being used by your recursion.
Ex:- If you pass a 10^5 array during each level of recursion you can calculate your max recursion level depending on the memory given by the compiler.

A segmentation fault occurs when a program attempts to access a memory location that it is not allowed to access, or attempts to access a memory location in a way that is not allowed (for example, attempting to write to a read-only location, or to overwrite part of the operating system).