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:
- Allocate array on heap - use
malloc()
, as other posters suggested. Do not forget tofree()
it (although formain()
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 inmain()
.
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;}