如何解决堆栈跟踪错误

时间:2014-09-08 17:35:30

标签: c++ cygwin runtime-error

我正在编写一个程序,通过试验部门获得素数。首先它筛选2^32以下的所有素数,然后测试2^64-1及其下方的素数。
使用下面提到的代码,我执行:

  

正在初始化...
  完成。
  710 [main] a 15444 cygwin_exception :: open_stackdumpfile:将堆栈跟踪转储到a.exe.stackdump。

我做错了什么?

代码:

#include <math.h>
#include <iostream>
#include <stdio.h>
using namespace std;

bool* SieveOfEratosthenes(unsigned long long number) {
    bool* prime = new bool[number + 1];
    for (unsigned long i = 0; i <= number; i++)
        prime[i] = true;
    // 0 and 1 are not prime, and we mark because we do not check in the
    // algorithm
    //(because will cause bad results, if we divide by 0, we go to hell, and if
    //we divide one by one, we will mark all numbers a nonprime.
    prime[0] = false;
    prime[1] = false;
    unsigned long squareRoot = sqrt(number);
    for (unsigned long i = 2; i <= squareRoot; i++) {
        // If is gray (Is prime)
        if (prime[i]) {
            // cout << i << ",";
            // We start j by the next multiple of i (that is: 2*i), and we
            // increase it by i each time until j is less than or equal to
            // sqrt(number)
            for (unsigned long j = i * i; j <= number; j += i)
                prime[j] = false;
        }
    }
    return prime;
}

int main() {
    printf("Initializing...");
    unsigned long number = 4294967295;
    unsigned long long c;
    bool* primes;
    unsigned long* p;
    p = new unsigned long[203280221];
    primes = SieveOfEratosthenes(number);
    for (unsigned long i = 0; i < number; i++) {
        if (primes[i] == true) {
            // cout << i << endl;
            p[c] = i;
            // cout << p[c] << endl;
            c++;
        }
    }
    delete[] primes;
    printf("done.\n");
    for (c = 18446744073709551615; c > 1; c -= 2) {
        unsigned long root = (unsigned long)sqrt(c);
        unsigned long i = 0;
        bool flag = true;
        while (p[i] <= root) {
            cout << "DEBUG: Test " << p[i];
            if (c % p[i] == 0) {
                flag = false;
                break;
            }
        }
        if (flag == true)
            cout << c << endl;
    }

    return 0;
}

1 个答案:

答案 0 :(得分:4)

异常最有可能是out of memory

您正在4294967295 bool功能中分配SieveOfEratosthenes。根据平台和编译器,bool可以是 1字节 4字节。使用bool大小1 byte,结果是4096Mb分配(4Gb),如果程序以32位编译,则确定错误。

主要是为p分配其他775Mb(假设unsigned long大小为4字节)

如果您正在使用GCC进行编译,请尝试添加参数-m64以在64位模式下进行编译,如果您在项目的属性中使用Visual Studio,则将目标更改为x64

您可以将bool数组更改为std::vector<bool>STL的大多数实施都会bit实施(在unsigned long中保存为4294967295 bool 32 bool值),这意味着511Mb将为{{1}}