Segmentation Fault in C/C++

Segmentation Fault, bus error or access violation is generally an attempt to access memory that the CPU cannot physically address. It occurs when the hardware notifies an operating system about a memory access violation.

Example

char *var1 = NULL; // Initialized to null, it's OK
char *var2; // Not initialized at all.
char *var3  = new char[20];  // allocated, fine
delete [] var3; // deleting var3, OK
delete var1; // may cause Segmentation Fault
delete var2; // may cause Segmentation Fault

Another Segmentation fault example

char *s = "hello";
     *s = 'H';

When the program containing this code is compiled, the string “hello” is placed in the section of the program executable file marked as read-only; when loaded, the operating system places it with other strings and constant data in a read-only segment of memory. When executed, a variable, s, is set to point to the string’s location, and an attempt is made to write an H character through the variable into the memory, causing a segmentation fault.

Common causes of Segmentation Fault

  • Improper format control string in printf or scanf statements:
    Make sure the format control string has the same number of conversion specifiers (%s) as the printf or scanf has arguments to be printed or read, respectively, and that the specifiers match the type of variable to be printed or read. This also applies to fprintf and fscanf.

  • Forgetting to use "&" on the arguments to scanf:
    Function scanf takes as arguments the format control string and the addresses of variables in which it will place the data that it reads in. The "&" (address of) operator is used to supply the address of a variable. It is common to forget to use "&" with each variable in a scanf call. Omitting the "&" can cause a segmentation violation.

  • Accessing beyond the bounds of an array:
    Make sure that you have not violated the bounds of any array you are using; i.e., you have not subscripted the array with a value less than the index of its lowest element or greater than the index of its highest element.

  • Failure to initialize a pointer before accessing it:
    A pointer variable must be assigned a valid address (i.e., appear on the left-hand-side of an assignment) before being accessed (i.e., appearing on the right-hand-side of an assignment). Make sure that you have initialized all pointers to point to a valid area of memory. Proper pointer initialization can be done several ways. Examples are listed below.

  • Incorrect use of the "&" (address of) and "*" (dereferencing) operators:
    Make sure you understand how these operators work. Know when they should be applied and when not to apply them. As mentioned above, it is common to forget to use "&" with each variable in a scanf call. Remember, scanf requires the address of the variables it is reading in. Especially, know when "&" and "*" are absolutely necessary and when it is better to avoid using them.