本文介绍了C ++数组分配分割故障11新手上路的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习C ++的算法在C + +通过Robert Sedgewick。现在我正在筛选Eratosthenes与用户指定的上界上最大的素数。当我运行代码与max 46349,它运行和打印出所有的素数高达46349,但是当我运行代码与最大46350,分段故障发生。有人可以帮助解释为什么吗?

I am learning C++ from Algorithms in C++ by Robert Sedgewick. Right now I am working on the Sieve of Eratosthenes with a user specified upper bound on the largest prime. When I run the code with max 46349, it runs and prints out all primes up to 46349, however when I run the code with max 46350, a Segmentation fault occurs. Can someone help to explain why?

./sieve.exe 46349
 2 3 5 7 11 13 17 19 23 29 31 ...

./sieve.exe 46350
 Segmentation fault: 11

代码:

#include<iostream>

using namespace std;

static const int N = 1000;

int main(int argc, char *argv[]) {
    int i, M;

    //parse argument as integer
    if( argv[1] ) {
        M = atoi(argv[1]);
    }

    if( not M ) {
        M = N;
    }

    //allocate memory to the array
    int *a = new int[M];

    //are we out of memory?
    if( a == 0 ) {
        cout << "Out of memory" << endl;
        return 0;
    }

    // set every number to be prime
    for( i = 2; i < M; i++) {
        a[i] = 1;
    }

    for( i = 2; i < M; i++ ) {
        //if i is prime
        if( a[i] ) {
            //mark its multiples as non-prime
            for( int j = i; j * i < M; j++ ) {
                a[i * j] = 0;
            }
        }
    }

    for( i = 2; i < M; i++ ) {
        if( a[i] ) {
            cout << " " << i;
        }
    }
    cout << endl;

    return 0;
}


推荐答案

        for( int j = i; j * i < M; j++ ) {
            a[i * j] = 0;
        }

46349 * 46349 不适合在 int 。

在我的机器上,更改 j 到 long 可以为更大的输入运行程序:

On my machine, changing the type of j to long makes it possible to run the program for larger inputs:

    for( long j = i; j * i < M; j++ ) {

根据您的编译器和架构,您可能必须使用 long long 才能获得相同的效果。

Depending on your compiler and architecture, you may have to use long long to get the same effect.

这篇关于C ++数组分配分割故障11新手上路的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-21 05:34