0

Possible Duplicate:
stack overflow c++

I have the following program for generating prime numbers:

#include<iostream> 
#include<cmath>
#include<algorithm>

#define MAX 10000000
using namespace std;

int main(int argc, const char *argv[])
{
    bool prime[MAX+1];
    fill_n(prime,MAX+1,true);
    int baseSqrt,i,j;
    baseSqrt = int(sqrt(MAX+1));
    for(i=2;i<=baseSqrt;i++){
        if(prime[i]){
            for(j=i+i;j<=MAX;j+=i){
                    prime[j]=false;
            }   
        }   
    }   
    return 0;
}

The program works fine for MAX value = 1000000. But when I increase the value to 10000000 the program gives segfault. I tried using gdb but it stops on main giving segfault there. I am using a 64 bit OS. Even if I remove MAX and write 10000000 rather than MAX, I get the same error. Where am I going wrong? Please help.

Community
  • 1
  • 1
Shehbaz Jaffer
  • 1,944
  • 8
  • 23
  • 30
  • 2
    The stack's size is usually very limited compared to the total amount of memory you can use. – chris Jan 06 '13 at 12:40

2 Answers2

5

You shouldn't declare very large arrays as local variables (i.e. on the stack), as the stack size is usually quite limited. Instead, dynamically allocate them with new[] and delete[]. Or for idiomatic C++, use a container class like std::deque.

Oliver Charlesworth
  • 267,707
  • 33
  • 569
  • 680
0

In this particular case, would it not be a reasonable idea to make "prime" a global variable. I do understand that global variables aren't always a good solution, but for this particular case, it would be a fairly obvious solution. It's not like MAX isn't a constant, so using new/delete or vector as a solution seems a little unnecessary.

And to answer the question of "is if slower to use 'new' vs global variable', then I can say that it's probably irrelevant. I used #define MAX 1000000000 in the above code, moved prime to be a global, and ran it using time, then altered the code to use new/delete, and it took around 0.5s longer - but the overall runtime is 20.4 or 20.9 seconds, so it's about 2% of the total runtime, and I'm pretty sure more than 2% can be gained by doing other things.

Mats Petersson
  • 126,704
  • 14
  • 140
  • 227