Hello, OnlineGDB Q&A section lets you put your programming query to fellow community users. Asking a solution for whole assignment is strictly not allowed. You may ask for help where you are stuck. Try to add as much information as possible so that fellow users can know about your problem statement easily.

What is segmentation fault?

+2 votes
asked Sep 19, 2017 by Jay
I am facing segmentation fault when I run program. What does it mean by segmentation fault?

2 Answers

0 votes
answered Sep 19, 2017 by Raj
selected Feb 26, 2018 by Admin
 
Best answer

Segmentation fault occurs when your program tries to read/write invalid memory location which is not accessible to program.
For example, if you try to write on NULL address pointed by pointer, then it can cause segmentation fault. 

#include <stdio.h>

int main()
{
    *(int*)0 = 0;
    return 0;
}

There can be other possible reasons you may try to access invalid address.

1. Pointer is not initialized with any proper address and dereferencing pointer later.

int *ptr;
*ptr = 123;

2. Accessing global array beyond size of array.

#include <stdio.h>
int arr[10]; // global array 
int main() {
  int i;
  for(i=0; i<1000; i++) 
    arr[i] = 1;
}

This is common cause when you are doing string operations and you may go beyond size of character array.

There could be other causes as well, but in short you would be trying to access invalid memory location that would give you segmentation fault. 

If your cause of segmentation is different than 2 possible causes mentioned over there, then share your code here via OnlineGDB "share" button. And lets figure out what causes you segmentation fault. 

commented Mar 1, 2018 by Shripad Rayewar (100 points)
commented Oct 11, 2018 by Dominic Wu (100 points)
A couple of things are incorrect:

1. scanf() takes an address for the second parameter. It should be &a[i] and &b[i]. See http://www.cplusplus.com/reference/cstdio/scanf/ for more info


2. With i being 5 at the end of the loop in line 32. This will be an array index out of bounds condition.

    c[i]=a[i]+b[i];
    
    printf("Addition Stored in third Array=");
    
    for (i=0;i<=4;i++)
    
    {
        
        printf("\nc[%d]=%d",i,c[i]);
        
        
    }
0 votes
answered Sep 20, 2017 by divya k (140 points)

Segmentation fault occurs when your program tries to read/write invalid memory location which is not accessible to program.

Welcome to OnlineGDB Q&A, where you can ask questions related to programming and OnlineGDB IDE and and receive answers from other members of the community.
...