当我在堆栈上进行大量内存分配时,C 程序崩溃

标签 c windows memory tabs allocation

当我使用 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/

相关文章:

python - 有人成功地使用 Pyinstaller 将数据文件捆绑到一个文件中吗?

Windows 性能分析器缺少 ImageId 事件

c++ - 将它们(函数)保存在内存中的同一位置

c - C for Linux 中的进程和无限循环

windows - 无法将 FOR 循环的输出分配给批处理文件中的另一个变量

python - 如何减少这个 numpy 梯度下降代码的内存占用?

python - 如何解决 Python 中的内存错误

c - 从函数返回一个二维数组到主函数

c - fprintf - 每行打印特定数量的字符

c - C/gcc 中的枚举类型检查