# Thread: Why do I get seg fault with large input?

1. ## Why do I get seg fault with large input?

By input I mean the command line argument. If I put 10, or 100, or 1000, it works, but 4000 gives a segmentation fault!

here is the code:

Code:
```/***************************************************************************
sieve.cpp  -  description
-------------------
begin                : Thu Oct 3 2002
copyright            : (C) 2002 by Will Herrick
email                : will.herrick2@verizon.net
***************************************************************************/
// This program finds the prime numbers from 1-1000 using the
// Sieve of Eratosthenes
/***************************************************************************
*                                                                         *
*   This program is free software; you can redistribute it and/or modify  *
*   the Free Software Foundation; either version 2 of the License, or     *
*   (at your option) any later version.                                   *
*                                                                         *
***************************************************************************/

#include <iostream>
#include <fstream>

using namespace std;

ofstream write;

int main(int argc, char* argv[])
{
int Numbers[1000];
int max;
int x;
int y;
int column = 0;

if(argc != 2) // meaning they didn't put in any options
{
cout << "Please put in the number you'd like to find the primes upto.";
return 0;
}
else
{
max = atoi(argv[1]);
}
write.open("primes.dat", ios::out);

// fill the number array
for(x = 0; x < max; x++) Numbers[x] = (x+1);

for(x = 1; x < (max - 2); x++) // start at 2 since we already know 1 isn't prime
{
if(Numbers[x] != 1 && Numbers[x] != 0) // 1 means its been "crossed off"
{
for(y = (x+1); y < (max-1-x); y++) // finds multiples of x
{
if(Numbers[y] % Numbers[x] == 0)
{
Numbers[y] = 1;
}
}
// the following provides some formatting for primes.dat
if(column < 8)
{
write << (x+1) << "\t"; // writes the prime number to file
column++;
}
else
{
write << (x+1) << endl;
column = 0;
}
Numbers[x] = 0; // "circled" - its prime
}
}
return 0;
}```

The purpose of the code is to print to a file all of the prime numbers from 1 to the number the user enters at run time. (it's called a sieve of Eratosthenes)

but like I said, if I run ./sieve 4000 I get a Segmentation Fault (running linux mandrake 9.0, KDevelop 2.1)

The error probably stems from me only using command line arguments on one other occasion, so i'm not very versed in them. Thanks!

2. Oh and I just tried and it will accept upto 1003 for input - 1004 gives a segmentation fault..

weird!

3. int Numbers[1000];
No wonder 4000 gives you a seg fault and 1000 doesn't. Dynamically allocate the memory based on the argument passed.

eg..
max = atoi(argv[i]);
int *Numbers = new int[max];

4. Wow I'm stupid, thanks!