Rockybilly
Rockybilly

Reputation: 4520

Invisible memory error in C++ sieve code

I have written a very basic sieve of eratosthenes with C++, however when the n is 1000000 (a million), the code crashes. I could not resolve the issue and now in need of help.

#include <iostream>
#include <vector>

using namespace std;

int main(){
    long n = 1000000,i ,j;
    vector<bool> arr(n, true);

    for(i = 2; i * i < n; i++){

        if(arr[i]){
            for(j = i + i; j <= n; j += i){
                arr[j] = false;
            }
        }
    }
    cout << "Made it here." << endl;
    return 0;
}

Some info:

Thanks for your help.

Edit: A more informing description of the error from Drmemory

Error #1: UNADDRESSABLE ACCESS beyond heap bounds: writing 0x0000000003921608-0x000000000392160c 4 byte(s)

Upvotes: 1

Views: 140

Answers (1)

Justin
Justin

Reputation: 25347

for(j = i + i; j <= n; j += i){
    arr[j] = false;

What happens when j == n? You access arr[n], which is out of bounds, as arr.size() == n.

This is undefined behavior. Your program may crash, or it may silently continue, or it may do something else. You can't reason about what will happen, because – by definition – the behavior isn't defined.

Upvotes: 1

Related Questions