title: C++ Array Allocation Segmentation Fault 11 Newbie
body: <p>I am learning C++ from Algorithms in C++ by Robert Sedgewick.  Right now I am working on the Sieve of Eratosthenes with a user specified upper bound on the largest prime.  When I run the code with max 46349, it runs and prints out all primes up to 46349, however when I run the code with max 46350, a Segmentation fault occurs.  Can someone help to explain why?</p>
  
  <pre><code>./sieve.exe 46349
   2 3 5 7 11 13 17 19 23 29 31 ...
  
  ./sieve.exe 46350
   Segmentation fault: 11
  </code></pre>
  
  <p>Code:</p>
  
  <pre><code>#include&lt;iostream&gt;
  
  using namespace std;
  
  static const int N = 1000;
  
  int main(int argc, char *argv[]) {
      int i, M;
  
      //parse argument as integer
      if( argv[1] ) {
          M = atoi(argv[1]);
      }
  
      if( not M ) {
          M = N;
      }
  
      //allocate memory to the array
      int *a = new int[M];
  
      //are we out of memory?
      if( a == 0 ) {
          cout &lt;&lt; "Out of memory" &lt;&lt; endl;
          return 0;
      }
  
      // set every number to be prime
      for( i = 2; i &lt; M; i++) {
          a[i] = 1;
      }
  
      for( i = 2; i &lt; M; i++ ) {
          //if i is prime
          if( a[i] ) {
              //mark its multiples as non-prime
              for( int j = i; j * i &lt; M; j++ ) {
                  a[i * j] = 0;
              }
          }
      }
  
      for( i = 2; i &lt; M; i++ ) {
          if( a[i] ) {
              cout &lt;&lt; " " &lt;&lt; i;
          }    
      }
      cout &lt;&lt; endl;
  
      return 0;
  }
  </code></pre>