Segmentation faults are common run-time error for C programs. When we run the program we will get segmentation violation
or segm4
or similar errors and the program exits. Segmentation faults generally observed inside weak or untested applications.
entation fault
Common Causes Of Segmentation Faults
There may be a lot of different causes for Segmentation Faults but there are some common ones which creates most of them.
- Improper format control string in
printf()
andscanf()
functions - Forgetting use of
&
on the arguments inscanf()
function - Accessing beyond the bound of an array
- Failure to initialize a pointer before accessing it
- Incorrect usage of
&
address and*
dereferencing operators
Segmentation Fault Examples
memset() Function
In this part we will examine segmentation faults. In the following code memset()
function line will create a segmentation fault.
#include<stdio.h> int main(void) { memset((char *)0x0, 1, 100); printf("HELLO POFTUT.COM \n"); return 0; }
And when we try to execute this code binary we will see following line.
$ ./a.out Segmentation fault (core dumped)

Array Bound
In this case we will exceed the array bounds which will create a seg fault.
#include<stdio.h> int main(void) { int foo[1000]; for (int i = 0; i <= 1000 ; i++) foo[i] = i; printf("HELLO POFTUT.COM \n"); return 0; }
Illegal Memory Access
Illegal memory access is similar to the Array Bound
situation.
#include<stdio.h> int main(void) { float *foo, *foo2; foo = (float*)malloc(1000); foo2[0] = 1.0; printf("HELLO POFTUT.COM \n"); return 0; }
Wrong scanf() Function Usage
scanf()
function is used to input data from console. This input will use some pointers which can create segmentation fault if not used properly.
#include<stdio.h> int main(void) { int foo = 0; scanf("%d", foo); printf("HELLO POFTUT.COM \n"); return 0; }
Finding Problem Location by Debugging
The best and easy way to find a segmentation fault is using debugger. Debug information will provide more details about the problem and related code part.