分段错误

A 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

但是我不知道是什么原因导致我的这个错误code.Please帮帮我。

您的数组 is_not_prime 的长度为 N。例如,在外层 for 循环的最后一圈,i 的值为 N-1。当 i 这么大时, is_not_prime[i*prime[j]] 将导致您写出数组的边界。

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

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

比较你的循环绑定检查和你的索引——它们不一样。 (我相信您打算在 for 循环中写入 i*prime[j]<N。)

您的程序因索引越界而崩溃。并且索引超出范围,因为您的算法无效。

因为如果您将 N 设置为更小的值,它仍然会崩溃

const int N = 3;

用铅笔和纸 运行 你的程序应该不难看出哪里出了问题...