c++ 第86行:字符2:运行时错误:存储到类型为'std::_Bit_type'的空指针(也称为'unsigned long')(stl_bvector.h)

elcex8rz  于 2023-08-09  发布在  其他
关注(0)|答案(1)|浏览(291)

我正在尝试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;
    }
};


我试图在网上找到解决方案,但仍然无法纠正它。
我知道错误大致意味着索引越界,但我不明白是怎么回事?请解释一下。

bakd9h0s

bakd9h0s1#

在访问prime[0]prime[1]之前不检查n值,n可以是0或1。
runtime error: store to null pointern为0的明确符号(向量没有数据,它是nullptr,向量的大小为0)。

相关问题