Status Stack Overflow in C with Simple Iteration

I recently started learning C. I'm using Code :: Blocks with MinGW and Cygwin GCC.

I made a very simple right sieve for the Project Euler 10 task, which prints primes below a certain limit for stdout. It works fine up to about 500,000 as a limit, but is higher than my compiled with minGW.exe failure, and the compiled GCC code throws an exception "STATUS_STACK_OVERFLOW".

I am puzzled by why, because the code is completely non-recursive, consisting of simple loops.

#include <stdio.h> #include <math.h> #define LIMIT 550000 int main() { int sieve[LIMIT+1] = {0}; int i, n; for (i = 2; i <= (int)floor(sqrt(LIMIT)); i++){ if (!sieve[i]){ printf("%d\n", i); for (n = 2; n <= LIMIT/i; n++){ sieve[n*i] = 1; } } } for (i; i <= LIMIT; i++){ if (!sieve[i]){ printf("%d\n", i); } } return 0; } 
+4
source share
3 answers

It looks like you cannot allocate 550,000 ints on the stack, instead allocate them dynamically.

 int * sieve; sieve = malloc(sizeof(int) * (LIMIT+1)); 
+4
source

Your main options are to store variables in a data segment when your piece of memory is larger than the stack:

  • allocating memory for an array on the heap using malloc (as @Binyamin explained)
  • storing an array in data / BSS segments by declaring the array as static int sieve[SIZE_MACRO]
+3
source

All memory in this program is allocated on the stack. When you increase the size of the array, you increase the amount of space required for the stack. In the end, the method cannot be called because there is not enough space on the stack to place it.

Or experience with malloc with an array (so it stands out on the heap). Or find out how to tell the compiler to allocate a larger stack.

+1
source

Source: https://habr.com/ru/post/1400066/


All Articles