Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"Status stack overflow" in C with simple iteration

I started to learn C recently. I use Code::Blocks with MinGW and Cygwin GCC.

I made a very simple prime sieve for Project Euler problem 10, which prints primes below a certain limit to stdout. It works fine until roughly 500000 as limit, but above that my minGW-compiled .exe crashes and the GCC-compiled one throws a "STATUS_STACK_OVERFLOW" exception.

I'm puzzled as to why, since the code is totally non-recursive, consisting of simple for 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;
}
like image 523
András Kovács Avatar asked Feb 22 '23 05:02

András Kovács


1 Answers

Seems like you cannot allocate 550000 ints on the stack, allocate them dynamically instead.

int * sieve;
sieve = malloc(sizeof(int) * (LIMIT+1));
like image 178
MByD Avatar answered Mar 03 '23 20:03

MByD