Segmentation Fault in the given Program

72 views Asked by At

I often come across segmentation fault,and even though I know it occurs because of accessing restricted memory,I don't seem to get as to how do I rectify it. I usually come across it, when I am calling another function.

#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
long int xyz(int n)
{
  vector<int> a;
  vector<int> b;


  for(int i=0;i<n;i++)
  {
      cin>>a[i];
  }
  for(int i=0;i<n;i++)
  {
     cin>>b[i];
  }
long int sum=0;

  for(int i=0;i<n;i++)
  {
   for(int j=i+1;j<n;j++)
    {
       sum=sum+((a[j]-a[i])*max(b[i],b[j]));
    }
  }


 return sum;

}


int main() 
{
  int n;
  long int final;
  cin>>n;
  for(int i=0;i<n;i++)
  {   int n;
      cin>>n;
      final=xyz(n);
      cout<<final<<endl;

   }

   return 0;
}
2

There are 2 answers

0
Sagar Kar On BEST ANSWER

You cant use the indexing of vector or [] unless you have already initialized that index by declaring size or by vec.push_back() method!

Refer to these two pieces of code for clarification

This code will not run (segmentation error):

int main()
{
 vector<int> a; //not initialized so cant be indexed directly
 cin>>a[0];
 cout<<a[0];
 return 0;
}

This part will run without problem:

int main()
{
 vector<int> a(5); //size initialized upto 5, so if indexed at a point greater than 4 it will be error
 cin>>a[0];
 cout<<a[0];
 return 0;
}

NOTE: You can see a new type of error being printed if you use the vec.at() operator and that error will probably mean the same!

Give a try at this erroneous code:

int main()
{
 vector<int> a;
 cin>>a.at(0);
 cout<<a.at(0);
 return 0;
}
3
Bathsheba On

In this particular case, you have not sized your two vectors a and b.

They are constructed with zero size by default.

vector<int> a(n); gives you n elements. Make a similar change to b and all should be well.

The behaviour of using [] to access an element of a vector outside its range is undefined.