-3

My block of code runs, but whenever I type in input, it returns Thread 1: EXC_BAD_ACCESS (code=1, address=0x4). I'm fairly new to coding, and was wondering what's wrong.

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

int main() {
    int x, count = 1;
    cin >> x;
    vector<int> sieve;
    fill(sieve.begin(), sieve.begin()+x-1, 1);
    while (count <= x) {
        for (int i = count+1; i <= x; i++) {
            if (sieve[i-1] == 1) {
                count = i;
                break;
            }
        }
        for (int i = count*count; i < x; i+=count) {
            sieve[i-1] = 0;
        }
    }
    for (int i = 0; i < x-1; i++) {
        if (sieve[i] == 1) {
            cout << i+1 << endl;
        }
    }
}
  • 2
    `vector sieve;` allocates no storage, so not only is `sieve.begin()+x-1` out of range, but so is `sieve.begin()`. `vector sieve(x);` ought to solve that. – user4581301 Mar 26 '19 at 18:24
  • 2
    To add on to the above comment, you need to allocate space for your sieve. So you might want `vector sieve(x)`. Or, you can even do `vector sieve(x, 1)`, which will allocate space for `x` ints and fill them all with `1`s already, so you won't need the fill afterwards. – Kevin Wang Mar 26 '19 at 18:25
  • I missed that. @KevinWang , that might have enough value-add to be worth an answer. I'll stop hunting for a duplicate. – user4581301 Mar 26 '19 at 18:28
  • @user4581301 Yeah, it seems to be tenacious to find a good duplicate. – πάντα ῥεῖ Mar 26 '19 at 18:34
  • So many to choose from. Picking out the best is hard. Googling "vector bad access" popped up [this as the first link](https://stackoverflow.com/questions/5342596/c-vector-bad-access) and it's pretty close, but I still think Kevin's point about auto filling the `vector` merits a longer life since it does show a better way to do this. – user4581301 Mar 26 '19 at 18:39
  • Turned my comment into an answer – Kevin Wang Mar 26 '19 at 19:21
  • Cool. Thanks guys – Griffin Wong Mar 27 '19 at 01:05

1 Answers1

1

You need to allocate space for your sieve. So you might want vector<int> sieve(x). Or, you can even do vector<int> sieve(x, 1), which will allocate space for x ints and fill them all with 1s already, so you won't need the fill afterwards.

Kevin Wang
  • 2,673
  • 2
  • 10
  • 18