Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array Segmentation Fault

I have a problem with the segmentation fault. Look:

#include<fstream>
using namespace std;
int main(){
    int n,i,vector[10001],vectorcopy[10001];
    ifstream in("program.in");
    ofstream out("program.out");
    in>>n;
    for(i=1;i<=n;i++){
        in>>vector[i];
        vectorcopy[i]=vector[i];
    }
    return 0;}

And the debugger says: Program recived signal SIGSEGV, Segmentation fault

Please, tell me what to do!


1 Answers

Your program is (mostly) working correctly, if the input file program.in is correct. I suppose your segmentation fault error is caused by:

  • bad input
  • the lack of input checking in your program

I got no errors with this program.in input file:

10
1
2
3
4
5
6
7
8
9
10

Other errors

I said "mostly" because there are a few other errors in your program. They are not causing trouble (C++ calls this "undefined behaviour") right now, but sooner or later they will:

  • for an array of size n, indexes start at 0 and end at n - 1; when using arrays, do not write your for statement like this:

    for (i = 1; i <= n; i++)
    

just rewrite it as:

    for (i = 0; i < n; i++)
  • you are not using the vectorcopy array
  • you are not writing anything to the program.out output file
like image 139
Danilo Piazzalunga Avatar answered Jul 15 '26 15:07

Danilo Piazzalunga