Getting a stack overflow exception when declaring a large array Getting a stack overflow exception when declaring a large array arrays arrays

Getting a stack overflow exception when declaring a large array


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:

  1. 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).
  2. 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).
  3. 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;}