代码之家  ›  专栏  ›  技术社区  ›  holo

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

  •  0
  • holo  · 技术社区  · 7 年前

    这个简单的程序在我用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
    

    C:\Users\senss\Desktop>bug
    hello
    function begin
    function end
    end of the program
    

    谢谢您!

    1 回复  |  直到 7 年前
        1
  •  1
  •   Yang Liu    7 年前

    Windows上的默认堆栈是 1MB

    int n[1000000] 是4bytes*1000000=4MB,所以它崩溃了。 当你把它换成10万的时候,它是40万,所以没问题。

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

    或者是纯C

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

    如果你不喜欢指针,可以考虑使用std smart pointer