Q: Segmentation fault while using vector in C++? 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;
}


A: 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.

A: 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?
