Question

I quickly wrote a primes program that uses the seive of eratosthenes. I get an appcrash when I run the program. I debugged it and it told me std::bad_alloc. The debugger will not tell me which line of my code the exception occured on but tells me which line of system code. My source is as follows. I am somewhat new to c++.

#include <iostream>
#include <vector>
#include <string>
#include <math.h>

using namespace std;

int main(int argc, char* argv[])
{
    unsigned long long numt;
    if(argc < 2) {
        cout << "Usage: "<<argv[0]<<" <primes until...>" << endl;
        return 1;
    }

    else if(atol(argv[1])) {
        cout << "Usage: "<<argv[0]<<" <primes until...>" << endl;
        return 1;
    }
    numt = atol(argv[1]);
    vector<bool> primes(numt);

    for each(bool b in primes) b = true;

    primes[0] = false;

    long double sqrtt = sqrt(numt);
    for(unsigned long long l = 0; l<=sqrtt; l++) {
        if(!primes[l]) continue;
        for(unsigned long long cl = l; cl < numt; cl+= l) primes[cl] = false;
    }

    for(unsigned long long l = 0; l<numt; l++) if(primes[l]) cout << l;

    return 0;
}

Please also inform me of any bad programming practices too, please.

Was it helpful?

Solution 4

1) You didn't assign numt a value, yet you use it to initialize the vector.

2) You don't check if l is out of bounds for primes[l] here (what if numt equals 1?):

for(unsigned long long l = 0; l<=sqrtt; l++) {
    if(!primes[l]) continue;

OTHER TIPS

Very bad practice: Compiling your code without all reasonable compiler warnings turned on, or ignoring compiler warnings.

The variable numt has no defined value. vector primes (numt) will therefore fail.

numt is not initialized, which means it can have any value, probably a big one. Which is problematic if you want to create a vector of that length, which causes the exception to be thrown.

You're not writing to numt so you probably get some ridiculously huge garbage value. When the line vector<bool> primes(numt) is evaluated, it tries to create a ridiculously huge dynamic array using the garbage value, which your OS fails to do because of excessive size.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top