我正在尝试Eratosthenes的Sieve并尝试leetcode中的问题,但我得到了这个错误。
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..
字符串
下面是我的代码:
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;
}
};
型
我试图在网上找到解决方案,但仍然无法纠正它。
我知道错误大致意味着索引越界,但我不明白是怎么回事?请解释一下。
1条答案
按热度按时间bakd9h0s1#
在访问
prime[0]
和prime[1]
之前不检查n
值,n
可以是0或1。runtime error: store to null pointer
是n
为0的明确符号(向量没有数据,它是nullptr
,向量的大小为0)。