title: Segmentation fault in C when using fgets and fscanf
body: <p>i'm trying to read the first line of a text file and then skip over it using fgets but it's giving me a seg fault, can someone help me? It worked before I added the fgets, therefore it seems that the fgets is the problem.</p>
  
  <p>Code</p>
  
  <pre><code>#include &lt;stdio.h&gt;
  #include &lt;stdlib.h&gt;
  #include &lt;sched.h&gt;
  #include &lt;unistd.h&gt;
  
  int main(int argc, char *argv[])
  {
      int N
      const int STACK_SIZE=65536;
      int col=0;
      int i;
      int j;
      FILE *file1;
      int s;
      int row=0;
      int prev='t';
      char m[1024];
  
      if(argc != 3)
      {
          fprintf(stderr, "Usage: %s &lt;Executable&gt; &lt;Input file&gt; &lt;Threads&gt;\n", argv[0]);
          exit(1);
      }
  
      file1=fopen(argv[1],"r");
      if(file1==NULL) //check to see if file exists
      {
          fprintf(stderr, "Cannot open %s\n", argv[1]);
          exit(1);
      }
  
      stack=malloc(STACK_SIZE);
      if(stack==NULL)
      {
          perror("malloc");
          exit(1);
      }
  
      if(atoi(argv[2]) == 0)
      {
          fprintf(stderr,"Threads has to be a number.\n");
          exit(1);
      }
  
      fscanf(file1,"%d",&amp;N);
      rewind(file1);
  
      fgets(m,sizeof(m),file1);
      while((s=fgetc(file1)) != EOF)
      {
          if(s == ' ')
          {
              prev='a';
              continue;
          }
          if(s == '\n' &amp;&amp; prev != '\n')
          {
              row++;
              if(col != N)
              {
                  fprintf(stderr, "File %s has incorrect columns.\n", argv[1]);
                  exit(1);
              }
              col=0;
              prev='a';
          }
          if(s != ' ' &amp;&amp; s != '\n')
          {
              col++;
              prev='a';
          }
      }
      if(row != N)
      {
          fprintf(stderr,"File %s has incorrect rows.\n", argv[1]);
          exit(0);
      }
      rewind(file1);
  
      for (i = 0; i &lt; N; i++)
      {
          for (j = 0; j &lt; N; j++)
          {
              fscanf(file1,"%d",&amp;A[i][j]);
          }
      }
  
      fclose(file1);
  }
  }
  </code></pre>
  
  <p><strong>EDIT 1:</strong>
  Fixed. Code placement was the only problem.</p>