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;
}
				
                        
You cant use the indexing of vector or
[]unless you have already initialized that index by declaring size or byvec.push_back()method!Refer to these two pieces of code for clarification
This code will not run (segmentation error):
This part will run without problem:
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: