Ernesto Campese
Ernesto Campese

Reputation: 73

Sieve of Eratosthenes C++ - Range Error at memory

I'm working on this simple code to use the Sieve, but there is an error that stops the program from compiling. Below you find the code:

// sieve_of_erathosthenes.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include "../../Library/std_lib_facilities.h"

int main()
{
    // Create a boolean array "prime[0..n]" and initialize
    // all entries it as true. A value in prime[i] will
    // finally be false if i is Not a prime, else true.
    int n = 30;
    vector<int>prime;

    for (size_t i = 0; i < n; i++) {
        prime.push_back(true);
    }

    for (int p = 2; p*p <= n; p++)
    {
        // If prime[p] is not changed, then it is a prime
        if (prime[p] == true)
        {
            // Update all multiples of p
            for (int j = p * 2; j <= n; j += p)
                prime[j] = false;
        }
    }

    cout << "Following are the prime numbers smaller than or equal to " << n << '\n';

    // Print all prime numbers
    for (int p = 2; p <= n; p++)
        if (prime[p])
            cout << p << " ";

    return 0;
}

The error is: Unhandled exception at 0x772308F2 in sieve_of_erathosthenes.exe: Microsoft C++ exception: Range_error at memory location 0x004FF670.

I'm a new student and I have difficulties to translate the debugger errors... Thanks, guys!

Upvotes: 0

Views: 143

Answers (1)

Tanuj Yadav
Tanuj Yadav

Reputation: 1297

In your for loops the termination condition should be p<n because your vector is of size n and vectors are 0-indexed.

so, accessing prime[n] goes out of range. This is the reason for the error.

Upvotes: 1

Related Questions