【发布时间】:2013-02-17 02:13:20
【问题描述】:
我正在通过 Robert Sedgewick 的 C++ 算法学习 C++。现在我正在研究 Eratosthenes 筛,用户指定了最大素数的上限。当我以最大 46349 运行代码时,它会运行并打印出最多 46349 的所有素数,但是当我以最大 46350 运行代码时,会发生分段错误。有人可以帮忙解释一下原因吗?
./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;
}
【问题讨论】:
-
分段错误通常是由超出分配的内存范围的写入引起的。您应该使用调试器(或添加打印语句)来跟踪程序的进度,以便找出发生这种情况的时间点。
-
请注意,如果分配失败,
new将不会返回NULL(除非指定了nothrow,它不在此处)。它会抛出一个std::bad_alloc异常。
标签: c++ memory-management segmentation-fault sieve-of-eratosthenes