0

**Segmentation fault for vector amicable **

While running this code I'm getting runtime error segmentation fault and I think based on the error I'm getting I think its from amicable vector. can anyone help me to understand why I'm getting segmentation fault and helping to find solution is much appreciated.

#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;

int factors(int x) {
    vector <int> result;
    int i = 1;
    while(i*i <= x) {
        if(x % i == 0) {
            result.push_back(i);
            if(x/i != i) {
                result.push_back(x/i);
            }
        }
        i++;
    }
    int sum=0;
    for(int p=0;p<result.size();p++)
        sum = sum + result[p];
    return sum - x;
}

int main() {
    
    int tests;
    cin >> tests;
    vector<int> sumar;
    for(int i=0;i<=100000;i++){
        if(i==0){
            sumar.push_back(0);
        }
        else {
            sumar.push_back(factors(i));
        } 
    }
    vector<int> amicable;
    for(int i=1;i<=100000;i++){
        int j = sumar[i];
        int c = sumar[j];
        if(i==c && i!=j){
            //cout << i << " " << j << endl;
            amicable.push_back(i);
        }
    }
    
    while (tests--){
        int n;
        cin >> n;
        int sum = 0;
        for(auto i : amicable){
            if(i>n)
                break;
            sum += i;
        }
        cout << sum << endl;
    }
    
    return 0;
}

I tried decreasing the limit from 100000 to 45000, its working fine with limit 45000 but I need values till 100000

thank you.

  • Have you tried with a debugger? – PMF Aug 06 '22 at 16:50
  • 6
    `int c = sumar[j];` - how certain are you that `j` is less than `sumar.size();`? – UnholySheep Aug 06 '22 at 16:51
  • 2
    You might consider using the `at()` function so an exception is thrown when you access the vectors out of range. Pairs well with a debugger so you can examine the state of the program at the point where the problem occurs. – Retired Ninja Aug 06 '22 at 16:53

0 Answers0