数组太大会导致 Visual Studio 中的堆栈溢出错误和 Atom 中的块
Too large of an array leads to a stack overflow error in Visual Studio and a block in Atom
我的程序是一个非常简单的带有任意参数的随机数生成器。我在 Windows 10 上使用 Atom。代码如下:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#define LEN 560000
void main() {
int x[LEN];
int i;
int m = 1234234;
int a = 1245;
int c = 3;
x[0] = 1;
for (i = 1; i < LEN - 2; i++) {
x[i + 1] = a * (x[i] + c) % m;
}
printf("%lf\n", ((double)x[LEN-5]) / m); /* as check */
}
我没有从终端收到任何东西,但是如果我改变了我想要生成的向量的长度,设置 LEN=500000
,我立即从终点站。此外,如果我将 Visual Studio 与相同的代码一起使用,我会因溢出而收到错误消息。
我不明白为什么如果我从 LEN=500000
转到 LEN=560000
程序没有执行。
以我的愚见,我认为这两个编译器(即 Atom 和 Visual Studio)中 应该有数组长度的截断 ,因为如果我将数组设为再过一段时间程序就不行了。
编辑: 第二个循环从 1
到 LEN-2
但问题仍然存在。
您正在 main()
中分配超过 2 MB 的自动存储空间。这是否超出应用程序可用的堆栈 space 并导致 堆栈溢出 取决于系统。您正在经历未定义的行为,这似乎仅在您访问具有高索引值的 x
元素时才会显现,但仅您定义具有超过可用堆栈 space 的自动存储的对象这一事实就足够了调用未定义的行为。
您可以在 运行 此程序时尝试修改初始堆栈大小,但没有可移植的方法来指定它:请查看您的系统文档以了解如何操作。
对于可移植的解决方案,您应该使用 malloc()
分配数组并使 x
成为指向 int
的指针:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#define LEN 560000
int main() {
int *x = malloc(sizeof(*x) * LEN);
int i;
if (x == NULL) {
fprintf(stderr, "memory allocation failure\n");
return 1;
}
int m = 1234234;
int a = 1245;
int c = 3;
x[0] = 1;
for (i = 1; i < LEN - 2; i++) {
x[i + 1] = a * (x[i] + c) % m;
}
printf("%lf\n", ((double)x[LEN]) / m); /* as check */
free(x);
return 0;
}
我的程序是一个非常简单的带有任意参数的随机数生成器。我在 Windows 10 上使用 Atom。代码如下:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#define LEN 560000
void main() {
int x[LEN];
int i;
int m = 1234234;
int a = 1245;
int c = 3;
x[0] = 1;
for (i = 1; i < LEN - 2; i++) {
x[i + 1] = a * (x[i] + c) % m;
}
printf("%lf\n", ((double)x[LEN-5]) / m); /* as check */
}
我没有从终端收到任何东西,但是如果我改变了我想要生成的向量的长度,设置 LEN=500000
,我立即从终点站。此外,如果我将 Visual Studio 与相同的代码一起使用,我会因溢出而收到错误消息。
我不明白为什么如果我从 LEN=500000
转到 LEN=560000
程序没有执行。
以我的愚见,我认为这两个编译器(即 Atom 和 Visual Studio)中 应该有数组长度的截断 ,因为如果我将数组设为再过一段时间程序就不行了。
编辑: 第二个循环从 1
到 LEN-2
但问题仍然存在。
您正在 main()
中分配超过 2 MB 的自动存储空间。这是否超出应用程序可用的堆栈 space 并导致 堆栈溢出 取决于系统。您正在经历未定义的行为,这似乎仅在您访问具有高索引值的 x
元素时才会显现,但仅您定义具有超过可用堆栈 space 的自动存储的对象这一事实就足够了调用未定义的行为。
您可以在 运行 此程序时尝试修改初始堆栈大小,但没有可移植的方法来指定它:请查看您的系统文档以了解如何操作。
对于可移植的解决方案,您应该使用 malloc()
分配数组并使 x
成为指向 int
的指针:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#define LEN 560000
int main() {
int *x = malloc(sizeof(*x) * LEN);
int i;
if (x == NULL) {
fprintf(stderr, "memory allocation failure\n");
return 1;
}
int m = 1234234;
int a = 1245;
int c = 3;
x[0] = 1;
for (i = 1; i < LEN - 2; i++) {
x[i + 1] = a * (x[i] + c) % m;
}
printf("%lf\n", ((double)x[LEN]) / m); /* as check */
free(x);
return 0;
}