c++ - 段错误

标签 c++ c segmentation-fault

我尝试了以下代码来判断素数:

const int N = 200000;
long prime[N] = {0};
long num_prime = 0;
int is_not_prime[N]={1,1};
void Prime_sort(void)
{
    for( long i = 2 ; i<N ; i++ )
    {
        if( !is_not_prime[i] )
        {
            prime[num_prime++] = i;
        }
        for( long j = 0; j<num_prime && i*prime[i]<N ; j++ )
        {
            is_not_prime[i*prime[j]] = 1;
        }   
    }   
}

但是当我运行它时,它会导致段错误! 这个错误我从来没有遇到过。我搜索了Google,它对段错误的解释如下:

A segmentation fault (often shortened to segfault) is a particular error condition that can occur during the operation of computer software. In short, a segmentation fault occurs when a program attempts to access a memory location that it is not allowed to access, or attempts to access a memory location in a way that is not allowed

但我不知道我的代码中出现这个错误的原因。请帮助我。

最佳答案

您的数组 is_not_prime长度为 N。例如,在外部 for 循环的最后一圈,i 的值为 N-1 。当i有那么大吗is_not_prime[i*prime[j]]会导致你写入的内容远远超出数组范围。

我不太确定什么 j<num_prime && i*prime[i]<N应该这样做,但这可能是错误的一部分。使用调试器单步执行程序,并查看程序崩溃时变量的值。

只需以不太复杂的方式重新编写程序,所有错误都会消失。

关于c++ - 段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30126079/

相关文章:

c++ - Boost Gzip 过滤器 : compile failes

C++错误通过指针在结构中设置字符串

c++ - 在 constexpr GLenum 数组中存储 OpenGL 颜色附件

c++ - 释放内存opencv

c++ - std::string::assign() 导致段错误

android - su -c 在 Android (Linux) 中给出 "[1] Segmentation fault "

c++ - 如何正确地将 float 与 int 相乘并获得仅受有效数字影响的结果?

c - 在 MacO 上启用 IPV6_RECVPKTINFO

c - 为什么这个普通的 C 程序被检测为病毒?

python - Nginx 后面的 Flask/Python 应用程序运行约 24 小时后出现 uWSGI 段错误