当我使用 Visual C++ 在 Windows 上编译并运行这个简单的程序时,它崩溃了:
#include <stdio.h>
void foo()
{
printf("function begin\n");
int n[1000000];
for(long int i = 0; i < 1000000; i++)
{
n[i] = 2;
}
printf("function end\n");
}
int main()
{
printf("hello\n");
foo();
printf("end of the program\n");
}
我用 cl bug.c
进行编译.
在这种情况下,控制台仅显示:
C:\Users\senss\Desktop>bug
hello
但是,当我将 1 000 000 值更改为 100 000 时,就没有问题了:
C:\Users\senss\Desktop>bug
hello
function begin
function end
end of the program
谢谢!
最佳答案
Windows 上的默认堆栈是 1MB
int n[1000000]
是 4bytes * 1000000 = 4MB,所以它崩溃了。
当你把它改成100000的时候,就是400K了,就OK了。
实际上,我认为您可能希望在堆而不是堆栈中分配大数组,以避免堆栈溢出。
int* a = new int[1000000];
...
delete [] a;
或者纯C语言
int* a = malloc(1000000 * sizeof(int));
...
free(a);
如果您不喜欢指针,请考虑使用 std smart pointer让事情变得更容易。
关于当我在堆栈上进行大量内存分配时,C 程序崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54361360/