-5

Why am I getting a segmentation fault in the following code? This code starts with an array s whose first element is 0. Then an array t whose elements are compliment of s and then t is appended to s until size of is greater than 1000. The user then inputs the number of queries and the element with index x of array s is printed.

#include <bits/stdc++.h>

using namespace std;

int duplication(int x){
     // Complete this function
     vector <int> s;
     vector <int> t;
     int i=0,j;
     int n=0;
     s.push_back(n);
     while(true){
         t.clear();
         for(j=0;j<s.size();j++){
             int k = 1 - s.at(j);
             t.push_back(k);
         }
        for(j=0;j<s.size();j++){
             s.push_back(t[j]);
        }
        if(s.size()>1000) break;
    }
    i=s[x];
    return i;
}

int main() {
    int q;
    cin >> q;
    for(int a0 = 0; a0 < q; a0++){
        int x;
        cin >> x;
        int result = duplication(x);
        cout << result << endl;
    }
    return 0;
}
Nitish
  • 3
  • 1
  • 1
    Shouldn't your second forloop check the size of t instead of s? – AresCaelum May 15 '17 at 13:33
  • 2
    You're getting a segfault because you don't know how to use your debugger to step through your code, one line at a time, in order to examine the contents of all variables, and inspect your program's logic as it's executing, in order to identify the bug and fix it yourself. That's why you're still getting a segfault. – Sam Varshavchik May 15 '17 at 13:35
  • Your second `for` loop is wrong. You're adding to `s` whilst checking its `size`, and as you are adding to `s` in the body of the loop the `for` loop will never exit. – Sean May 15 '17 at 13:35
  • Passing in any value of x > 1000 has a potential to segfalt also, – stark May 15 '17 at 13:37

2 Answers2

1

For the 2nd loop, I believe it should be

 for(j=0;j<t.size();j++)

Also, i=s[x] Should probably check that x is with the bounds of indexes for s.

Ðаn
  • 10,934
  • 11
  • 59
  • 95
lostbard
  • 5,065
  • 1
  • 15
  • 17
0

Your issue is the second for loop.

for(j=0;j<s.size();j++){
    int k = 1 - s.at(j);
    t.push_back(k);
}

for(j=0;j<s.size();j++){ // First iteration size of S is 1, Size of T is 1
    s.push_back(t[j]);   // Size of s is now 2.
                         // Loop iteration comes around again j = 1 which is < 2
                         // t has a size of 1, you are accessing the 2nd index
                         // which is memory that you do not own.
}

The size of s will be resolved every iteration as it is constantly changing, you can either store a variable to track the size of s or use the size of t, but be wary that if the size of s is ever larger then t and you are storing the size of s you will have the same issue.

Read up on Segmentation faults here: What is a segmentation fault?

Community
  • 1
  • 1
AresCaelum
  • 1,558
  • 1
  • 13
  • 18