【问题标题】:C program crash when I do a big memory allocation on the stack [duplicate]当我在堆栈上分配大量内存时,C 程序崩溃 [重复]
【发布时间】:2019-06-19 01:22:24
【问题描述】:

当我使用 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 上,默认的进程策略只有一个 MiB。
  • int n[1000000]; 更改为int *n = malloc(1000000 * sizeof(int)); if (!n) return;
  • 欢迎来到 Stack Overflow! [双关语] :)
  • 感谢您的帮助和解释,我会修复它!

标签: c windows memory tabs allocation


【解决方案1】:

Windows 上的默认堆栈是1MB

int n[1000000] 是 4bytes * 1000000 = 4MB,所以它崩溃了。 当您将其更改为 100000 时,它是 400K,所以没关系。

在实践中,我认为您可能希望在堆而不是堆栈中分配大数组以避免堆栈溢出。

int* a = new int[1000000];
...
delete [] a;

或纯C

int* a = malloc(1000000 * sizeof(int));
...
free(a);

如果您不喜欢指针,请考虑使用 std smart pointer 以使事情变得更容易。

【讨论】:

  • 标签是C,不是C++。
猜你喜欢
  • 1970-01-01
  • 2017-01-04
  • 1970-01-01
  • 1970-01-01
  • 2016-03-02
  • 2014-05-22
  • 1970-01-01
  • 2011-12-01
  • 1970-01-01
相关资源
最近更新 更多