I'm trying Sieve of Eratosthenes and trying a problem in leetcode but I'm getting this error.
Line 86: Char 2: runtime error: store to null pointer of type 'std::_Bit_type' (aka 'unsigned long') (stl_bvector.h)
SUMMARY: UndefinedBehaviorSanitizer: undefined-behavior /usr/bin/../lib/gcc/x86_64-linux-gnu/9/../../../../include/c++/9/bits/stl_bvector.h:95:2..
below is my code :
class Solution {
public:
int countPrimes(int n)
{
int count = 0;
vector<bool> prime(n, true);
prime[0] = prime[1] = false;
for (int i = 2; i < n; i++) {
if (prime[i]) {
count++;
for (int j = i * 2; j < n; j = j + i) {
prime[j] = 0;
}
}
}
return count;
}
};
I have tried finding solutions online but still unable to rectify it.
I know that error roughly means a index is getting out of bounds but I cant understand how? please explain that.
You don't check n
value before accessing prime[0]
and prime[1]
, n
can be 0 or 1.
runtime error: store to null pointer
is a clear sign that n
is 0 (the vector does not have data, it's nullptr
and vector's size is 0).