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.
One method to prevent stack overflow is to track the stack pointer with test and measurement methods. Use timer interrupts that periodically check the location of the stack pointer, record the largest value, and watch that it does not grow beyond that value.
Usually you need to create such an array dynamically on the heap. int *integer_array = (int*)malloc(2000000 * sizeof(int)); float *float_array = (float*)malloc(2000000 * sizeof(float)); The array might be too large for stack allocation, e.g. if used not globally, but inside a function.
The most-common cause of stack overflow is excessively deep or infinite recursion, in which a function calls itself so many times that the space needed to store the variables and information associated with each call is more than can fit on the stack.
Introduction to C++ stack overflow. The following article provides an outline for C++ stack overflow. Stack overflow is a software bug which occurs when a program tries to access more memory than the available stack size, which results in the crashing of the program. Stack is Last in First Out data structure (LIFO).
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:
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).static
to declaration will limit the visibility to unit).static
- in this case it will be allocated in data segment, but visible only in main()
.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With