Getting a stack overflow exception when declaring a large array

The following code is generating a stack overflow error for me

int main(int argc, char* argv[])
{
    int sieve[2000000];
    return 0;
}

How do I get around this? I am using Turbo C++ but would like to keep my code in C

EDIT:

Thanks for the advice. The code above was only for example, I actually declare the array in a function and not in sub main. Also, I needed the array to be initialized to zeros, so when I googled malloc, I discovered that calloc was perfect for my purposes.

Malloc/calloc also has the advantage over allocating on the stack of allowing me to declare the size using a variable.


Your array is way too big to fit into the stack, consider using the heap:

int *sieve = malloc(2000000 * sizeof(*sieve));

If you really want to change the stack size, take a look at this document.

Tip: - Don't forget to free your dynamically allocated memory when it's no-longer needed.


There are 3 ways:

  • Allocate array on heap - use malloc() , as other posters suggested. Do not forget to free() it (although for main() it is not that important - OS will clean up memory for you on program termination).
  • Declare the array on unit level - it will be allocated in data segment and visible for everybody (adding static to declaration will limit the visibility to unit).
  • Declare your array as static - in this case it will be allocated in data segment, but visible only in main() .

  • You would be better off allocating it on the heap, not the stack. something like

    int main(int argc, char* argv[])
    {
        int * sieve;
        sieve = malloc(20000);
        return 0;
    }
    
    链接地址: http://www.djcxy.com/p/4856.html

    上一篇: 具体来说,铸造malloc的结果有什么危险?

    下一篇: 声明大型数组时发生堆栈溢出异常