A segmentation fault in C is an error that occurs when a program attempts to access a memory location it does not have permission to access. This error is caused by accessing memory that "does not belong to you". Some common scenarios that can cause segmentation faults are:
- Modifying a string literal
- Accessing an address that is freed
- Accessing out-of-array index bounds
- Improper use of scanf()
- Stack overflow
- Dereferencing uninitialized pointer
Segmentation faults are often associated with a file named "core" and are caused by a program trying to read or write an illegal memory location. In practice, segfaults are almost always due to trying to read or write a non-existent array element, not properly defining a pointer before using it, or accidentally using a variables value as an address. To fix segmentation faults, one should be careful about the causes mentioned above. Some tips to avoid segmentation faults include avoiding modifying string literals, being careful when using pointers, considering the buffer and stack size before storing the data to avoid buffer or stack overflow, checking for bounds before accessing array elements, and using scanf() and printf() carefully to avoid incorrect format specifiers or buffer overflow.