title: Segmentation fault in C with only certain inputs
body: <p>Okay, so I'm trying to solve the Knapsack problem. </p>
  
  <p>On small input cases the program runs with no problem and provides the optimal solution, however when the input size is large, or rather the numbers in the input file become large, the program gives me a segmentation fault. I don't quite get why is this happening since the max value of INT exceeds any of these numbers too.</p>
  
  <p>Here's my code.</p>
  
  <pre><code>    #include&lt;stdio.h&gt;
      #include&lt;stdlib.h&gt;
      int main(void)
      {
          int W,n,i,j,k ;
          scanf("%d %d",&amp;W,&amp;n); // capacity of knapsack and number of total items
          int value[n+1],weight[n+1];
          int** A;
          A = (int **)malloc((n+1)*sizeof(int*));
          for(i=0;i&lt;W+1;i++)
              A[i]=(int *)malloc(sizeof(int)*(W+1));
          for(i=1;i&lt;n+1;i++)
          {
              scanf("%d %d",&amp;value[i],&amp;weight[i]); //taking value and weight of each item
          }
          for(i=0;i&lt;W+1;i++)
              A[0][i]=0;
          for(i=0;i&lt;n+1;i++)
              A[i][0]=0;
          for(i=1;i&lt;n+1;i++)
          {   
              for(j=1;j&lt;W+1;j++)
              {
                  if(j-weight[i]&lt;0)
                  {
                      A[1][j]=A[0][j];
                  }
                  else
                  {
                      if(A[0][j]&gt;A[0][j-weight[i]]+value[i])
                          A[1][j]=A[0][j];
                      else
                          A[1][j]=A[0][j-weight[i]]+value[i];
                  }
              }
              for(k=0;k&lt;W+1;k++)
                  A[0][k]=A[1][k];
          }   
          int max=0;
          i=1;
          for(i=0;i&lt;2;i++)
              for(j=0;j&lt;W+1;j++)
              {
                  if(A[i][j]&gt;max)
                      max=A[i][j];
              }
          printf("%d\n",max);
          return(0);
      }
  </code></pre>
  
  <p>It runs perfectly for this input <a href="http://spark-public.s3.amazonaws.com/algo2/datasets/knapsack1.txt" rel="nofollow">http://spark-public.s3.amazonaws.com/algo2/datasets/knapsack1.txt</a></p>
  
  <p>But when the input size is the one given in the link, it provides a seg fault <a href="http://spark-public.s3.amazonaws.com/algo2/datasets/knapsack2.txt" rel="nofollow">http://spark-public.s3.amazonaws.com/algo2/datasets/knapsack2.txt</a>
  Thanks for the help!</p>