# I. Introduction
- Environment Setting:
- Ubuntu Linux: 24.04.1 LTS
- gcc: 13.3.0
- What is segmentation fault?
- How can segmentation occurs?
# II. Experiment
## Case 1: Invalid write to a read-only section
```C=
int main()
{
char *s = "Hello World";
*s = "H";
return 0;
}
```
- Compile the `.c` file into an object file using the following command.
```terminal
$ gcc segFault.c -g -o segFault
```
- The error message occurs after executing the`./segFault` command.
::: warning
Segmentation fault (core dumped)
:::
- This error is due to an invalid write to read-only memory. A string literal is stored in a read-only memory section.
- Solution:
- This code can be corrected by using an array instead of a character pointer, and this allocates memory on stack and initializes it to the value of the string literal.
```C=
int main()
{
char s[] = "Hello World";
s[0] = "H";
return 0;
}
```
## Case 2: Null pointer derefence
```C=
#include <stdlib.h>
#include <stdio.h>
int main()
{
int *ptr = NULL;
printf("%d", *ptr);
return 0;
}
```
- There is no any warning or error message after compiling this `.c` file into an object file.
- The same error message occurs aftering executing it.
::: warning
Segmentation fault (core dumped
:::
- Deferecing a null pointer and assigning value to it also causes a segmentation fault as the code follows:
```C=
#include <stdlib.h>
#include <stdio.h>
int main()
{
int *ptr = NULL;
*ptr = 1;
printf("%d",*ptr);
return 0;
}
```
## Case 3: Buffer overflow
```C=
#include <stdlib.h>
#include <stdio.h>
int main()
{
char s[] = "Hello World";
printf("%s", s[20]);
return 0;
}
```
- The code above accesses the character array `s` beyond its upper boundary
- No error message is prompted after compiling it into an object file.
- However, the same error message is prompted after executing it.
::: warning
Segmentation fault (core dumped)
:::
## Case 4: Stack overflow
```C=
int main()
{
return main();
}
```
- The infinite recursive call leads to a stack overflow error because the called function is allocated in stack section.
- This case is similar to the other cases presented above. No error message is prompted after compiling it. However, a *segmentation fault* occurs after executing it.
# III. Reference
- [Segmentation fault](https://en.wikipedia.org/wiki/Segmentation_fault)