1

This simple program crash when I compile and run it on Windows with Visual C++:

#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");
}

I compile with cl bug.c.

In this case, the console only displays:

C:\Users\senss\Desktop>bug
hello

However, when I change the 1 000 000 value to 100 000, there is no problem :

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

Thank you!

Mark
  • 88
  • 2
  • 10
holo
  • 331
  • 2
  • 13

1 Answers1

1

The default stack on Windows is 1MB

int n[1000000] is 4bytes * 1000000 = 4MB, so it crashes. When you change it to 100000, it's 400K so it's OK.

In practice I think you may want to allocate large array in heap instead of stack to avoid stack overflow.

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

or in pure C

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

If you don't like pointers, consider using a std smart pointer to make things easier.

Yang Liu
  • 117
  • 6