大小大于 210 万时 C 数组初始化错误
C array initialization error when size is larger than 2.1 million
我是 C 的新手,我编写了一个简单的程序来查找素数。但是,当我使用大于 ~210 万的 n 值时,程序在 bool arr[n+1];
处的第 25 行停止工作。我使用了 gdb 调试器,这是异常消息:
___chkstk_ms(未知 Source:0)
[Unknown/Just-In-Time编译代码](未知Source:0)。
出于某种原因,当我设置 n=2,075,000 时,我得到了这个错误:
msvcrt.dll!msvcrt!_setjmpex(未知 Source:0)
否则它适用于较低的值。
#include <stdio.h>
#include <stdbool.h>
#include <math.h>
int main()
{
printf("Up to which number do you need to count how many prime numbers there are? ");
int n;
scanf("%i", &n);
getchar();
if (n<0)
{
printf("Wrong input kind. Only natural numbers are accepted. \n");
return -1;
}
else if (n<2)
{
printf("There are 0 prime numbers");
return 0;
}
// Initialize an array representing all number up to including n.
// 0 and 1 are not prime, init the others as being prime
bool arr[n+1];
arr[0] = arr[1] = false;
for (int i = 2; i<=n; i++) arr[i] = true;
for (int i = 2; i<=sqrt(n); i++)
{
if (arr[i]) //if prime number
{
for (int k = i*i; k<=n; k+=i) //set its multiples as non-prime
{
arr[k] = false;
}
}
}
int count = 0;
for (int i = 2; i<=n; i++)
{
if (arr[i]) count++;
}
printf("In total, there are %i prime numbers up to %i\n", count, n);
return 0;
}
局部变量通常在堆栈上创建,堆栈数量有限space。在大多数情况下,数组中超过 200 万个元素将溢出堆栈,从而导致程序崩溃。
改为使用 malloc
在具有更高限制的堆上创建内存。
bool *arr = malloc(sizeof(bool) * (n+1));
我是 C 的新手,我编写了一个简单的程序来查找素数。但是,当我使用大于 ~210 万的 n 值时,程序在 bool arr[n+1];
处的第 25 行停止工作。我使用了 gdb 调试器,这是异常消息:
___chkstk_ms(未知 Source:0) [Unknown/Just-In-Time编译代码](未知Source:0)。
出于某种原因,当我设置 n=2,075,000 时,我得到了这个错误:
msvcrt.dll!msvcrt!_setjmpex(未知 Source:0)
否则它适用于较低的值。
#include <stdio.h>
#include <stdbool.h>
#include <math.h>
int main()
{
printf("Up to which number do you need to count how many prime numbers there are? ");
int n;
scanf("%i", &n);
getchar();
if (n<0)
{
printf("Wrong input kind. Only natural numbers are accepted. \n");
return -1;
}
else if (n<2)
{
printf("There are 0 prime numbers");
return 0;
}
// Initialize an array representing all number up to including n.
// 0 and 1 are not prime, init the others as being prime
bool arr[n+1];
arr[0] = arr[1] = false;
for (int i = 2; i<=n; i++) arr[i] = true;
for (int i = 2; i<=sqrt(n); i++)
{
if (arr[i]) //if prime number
{
for (int k = i*i; k<=n; k+=i) //set its multiples as non-prime
{
arr[k] = false;
}
}
}
int count = 0;
for (int i = 2; i<=n; i++)
{
if (arr[i]) count++;
}
printf("In total, there are %i prime numbers up to %i\n", count, n);
return 0;
}
局部变量通常在堆栈上创建,堆栈数量有限space。在大多数情况下,数组中超过 200 万个元素将溢出堆栈,从而导致程序崩溃。
改为使用 malloc
在具有更高限制的堆上创建内存。
bool *arr = malloc(sizeof(bool) * (n+1));