A segmentation fault is a particular error condition that can be occur during the operation of computer software.A segmentation fault occurs when a program attempts to access a memory location that is not allowed to access, or attempts to access a memory that is not allowed.For example attempting to write a read only location or to overwrite to the memory where a part of operating system is there.
On Unix/Linux-like operating systems, a process that accesses invalid memory receives the SIGSEGV signal. Segmentation faults are commonly referred to as segfaults. Here is some example that create segmentation faults.
char *str = “india”;
*str = ‘H’;
When the program containing this code is compiled, the string “india” is placed in the section of program marked as read only. when loaded the OS places it with other string and constant data in a read only segment of memory. when executed ,the variable str is pointed to that string location and attempts to write ‘H’ into the memory which cause segfaluts.
Some of the common mistake which leads segfault are given below
- Dereferencing NULL
- Dereferencing an uninitialized pointer
- Dereferencing a pointer that has been freed or deleted in c++ or that has gone out of scope
- Writing off end of the array