Reputation: 4520
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:
n = 100000
or n = 10000000
does not give errors (very strange) and code works fine, so values more than a million does not give problems while one million gives an error (crash)."Made it here."
1 total unaddressable access(es)
, which I could not find.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
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