Question

I'm implementing the sieve of eratosthenes algorithm in C++, and I've run into a problem. When I initialize my array to a very large value, like 1 million, it breaks because I'm allocating too large of an array to the stack. The answer in C would be to use malloc like this Sieve of Eratosthenes , but this solution does not work in C++ (to the best of my knowledge). Any ideas on how I could get this program to work with very large numbers by allocating the array in the heap instead of the stack? Thanks.

To see the problem I'm having, change the code below int integerList[1000], change 1000 to 1000000 or higher.

int main(void)
{
int userInput = 0;
int integerList[1000] = {};

cout << "Please pick a number to find all prime numbers " 
         << "from 2 to that number: " << endl;
//for the sake of writing out algorithm only, assume correct input
cin >> userInput;

//initialize array
for (int i = 2; i <= userInput; i++)
{
    integerList[i] = i;
}

//implementation of the algorithm
for (int i = 2; i < userInput; i++)
{
    if (integerList[i] != 0)
    {
        for (int j = 2; j < userInput; j++)
        {
            integerList[j*integerList[i]] = 0;
            if (integerList[i] * j > userInput)
            {
                break;
            }
        }
    }
}
for (int i = 0; i < userInput; i++)
{
    if (integerList[i] != 0)
    {
        cout << integerList[i] << " ";
    }
}
system("Pause");
return 0;
}
Was it helpful?

Solution

Allocating an array of size that large on the stack leads to stack overflow. To allocate it on the heap, you can do:

int *integerList = new int[1000000];

Or better, use a std::vector instead.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top