-1

I've been trying to implement the Eratosthenes sieve in C++. I am using the Dev C++ 5.11 compiler and every time I run my code, the compiler crashes. For a smaller array value (n = 10000), the program runs successfully, but prints garbage values in the text file (Please find image attached). I am an amateur in programming and have been working over this issue for over a day now. Would be glad for any help. Thanks for your time! :)

#include <iostream>
using namespace std;
#include <fstream>

int main(){
 ofstream myfile("Prime.txt");
 int n = 1000000;
 int prime[n] = {0};
 for (int i = 2; i <= n; i++){
   for (int j = i*i; j <= n; j+=i){
    prime[j - 1] = 1;
   }
 }
 for (int i = 2; i <= n; i++){
  //cout<<prime[i-1]<<endl;
  if (prime[i - 1] == 0)
   myfile<<i<<" ";
 }
 myfile.close();
 return 0;
}
Severus
  • 131
  • 5
  • I think you're going to get something out of this: ["Why does a large local array crash my program?"](https://stackoverflow.com/questions/22945647/why-does-a-large-local-array-crash-my-program). In case you care, it was the top answer retrieved by simply typing `[cpp] large array crash` in that search box you'll find on the upper-right corner of the page you're viewing right now. – WhozCraig May 20 '16 at 05:29
  • Sorry I forgot to mention. I've tried initiating it as a dynamic array already. It still gives the same error. Besides, there were suggestions elsewhere to define the array globally. Didn't work. – Severus May 20 '16 at 19:33
  • I was going to type up a big long answer, but since you never updated your question with more facts and the alternate version of the code that performs array allocation dynamically, I'll just tell you here. Assuming you're (a) being truthful and did, in fact, code a dynamic attempt at this, and (b) still experienced the same problem, I believe it to be an issue of integer overflow, and with that, your code invokes undefined behavior. Ask yourself this: given `i*i` , and the fact that `j` is `int`, what is the maximum value of `i` that can be squared and still fall below `INT_MAX`? – WhozCraig May 21 '16 at 21:52
  • Answer: `46340` on an implementation with 32bit signed `int` (which your 64bit OS will likely still use, reserving `long` to hold a full 64bit signed integral type). In short, your `1000000` is considerably larger than the largest possible value that, squared, falls below `INT_MAX`. Best of luck. – WhozCraig May 21 '16 at 21:54

1 Answers1

-1

maybe the array is to large. A 32-Bit compiler has a limit factor for the maximum size (4 GB limit).

1.000.000 * 4 Byte (32 Bit) = 4.000.0000 Byte

4.000.000 Byte / 1024 / 1024 = ~3,8 GB

Rico
  • 1
  • 1