"EXC_BAD_ACCESS" When using an array C++

1.3k views Asked by At

I'm trying to make a sieve function for finding prime numbers. The sieve itself consists of an array who's size is dependent on the input value of the function. Everything is fine for small numbers (<~1000000) but larger input values cause the program to give a "bad access" error when trying to change the value of element 0 of the array (Marked in the code block).

void psieve(uint64_t p)
{
    bool flags[p];
    flags[0]=false;        //This is the line throwing the error (according to xcode)
    flags[1]=false;
    for (uint64_t i=2; i<p; i++) {
        flags[i]=true;
    }
    for (uint64_t i=0; i<(uint64_t)sqrtl(p); i++) {
        if (flags[i]) {
            for (uint64_t j=i*i; j<p; j+=i) {
                flags[j]=false;
            }
        }
    }
    for (uint64_t i=0; i<p; i++) {
        if (flags[i]) {
            cout<<i<<"\n";
        }
    }
}

The specific error being thrown is "EXC_BAD_ACCESS (code=1, address=0x[This is a different hex number every time])"

Any help would be greatly appreciated.

1

There are 1 answers

1
Carl Norum On BEST ANSWER

It appears that your system has a downward growing stack. When p is too large, writing to its lower indices causes a stack overflow. Allocate p using a different method - std::vector might be a good choice, for example. Variable length arrays aren't a C++ feature anyway - your compiler is just supporting it as an extension.