4

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;
}
1
  • Try to set a higher ulimit. Allocating 550000 integers on the stack can cause that. Commented Mar 6, 2012 at 17:34

3 Answers 3

4

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

int * sieve;
sieve = malloc(sizeof(int) * (LIMIT+1));
Sign up to request clarification or add additional context in comments.

1 Comment

For a short-term solution you can also adjust your compiler settings. Not a good idea if you wake up one day and say that you need 55000000 instead of 550000.
3

Your basic options are to store variables in data segment when your memory chunk is bigger than stack:

  • allocating memory for array in heap with malloc (as @Binyamin explained)
  • storing array in Data/BSS segments by declaring array as static int sieve[SIZE_MACRO]

1 Comment

+1 for the comment about static. Just be aware that it means your code is no longer reentrant and the initializer will only be invoked once--neither of which is usually an issue for a function called main().
1

All the memory in that program is allocated on the stack. When you increase the size of the array you increase the amount of space required on the stack. Eventually the method cannot be called as there isn't enough space on the stack to accomodate it.

Either experiement with mallocing the array (so it's allocated on the heap). Or learn how to tell the compiler to allocate a larger stack.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.