Let's learn about Segmentation Fault

Let's learn about Segmentation Fault

Segmentation Fault

Memory Management

In C Programming language, we have the capability to access the memory and manipulate the data by using pointers. Pointers stores the address of a variable. Let us write a small piece of code, I'll explain it.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void){
  int c = 9;
  int *p = &c;
}

Here, I declared an integer with name c and assigned value 9. There is another variable which is p which stores the address of c. In C Programming language we have a different notation which stores the address of another variable by giving an * symbol before a variable name.

Suppose if I want a pointer array Like this,

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void){
  int *p = malloc(4 * sizeof(int));
  free(p);
}

Here, pointer p has 4 integer bytes of memory. Actually it can store 4 values they are 0-indexed like an array. But What happens if we access the memory which we don't have the access or we don't have the right to access? Do you think about it?

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void){
  int *p = malloc(4 * sizeof(int));
  *p[0] = 8;
  *p[1] = 9;
  *p[4] = 2;

  free(p);
}

Yeah, that is segmentation fault. We cannot access the memory that is out of our bounds. Our computer may or may not have the data in that.

Not only by using the pointer, we may get these errors while using arrays of fixed size.

#include <stdio.h>
int main(void){
  char s[4];
  scanf("%s", s); // helloooooooooooooooooooooooo
  printf("%s\n", s);
}

Here we can see, it is clearly exceeding the size of the input s, and output is Segmentation fault.

Yeah, You reached the end of the article, Thanks for reading!!