title: Invalid read of size 4 on fscanf
body: <p>Running my program through valgrind, I'm getting an invalid read of size 4 error in the following code (I think at the line where fscanf is called)</p>
  
  <p><strong>Important Info</strong>: <code>numIntegers</code> is the maximum number of integers that can be read, while <code>numsInFile</code> specifies the amount of integers present in the file. </p>
  
  <p>I use the minimum of the two to initialize the array. The reason for this is because if <code>numIntegers</code> is <code>100</code> and there are <code>22</code> integers in the file, I only want an array of size <code>22</code>.  If numIntegers is <code>22</code> and there are <code>100</code> integers in the file, I still want an array of size <code>22</code> since only <code>22</code> can be read.</p>
  
  <p>Here is my code:</p>
  
  <pre><code>// Get number of integers (first number)
  int numsInFile;
  fscanf(fp, "%d", &amp;numsInFile);
  
  // find minimum of numstoread and numintegers and use that as counttouse
      if(numsInFile &lt; numIntegers)
          countToUse = numsInFile;
      else
          countToUse = numIntegers;
  
  // Initialize the integers array with the minimum value as well - since it will only store this many
  integers = malloc(sizeof(int) * countToUse);
  
  for(int i = 0; i &lt; numsInFile; i++){
      if(i &lt; numIntegers){
          int currInt;
          if(fscanf(fp, "%d", &amp;currInt) == 1)
              integers[i] = currInt;
          else
              break;
      }
      else
          break;
  }
  </code></pre>
  
  <p>Any help is appreciated ahead of time. I can't for the life of me figure out why I'm getting this error in valgrind...</p>
  
  <h2>Code edited - No more errors</h2>
  
  <pre><code>// Get number of integers (first number)
  int numsInFile;
  if( fscanf(fp, "%d", &amp;numsInFile) != 1)
      fprintf(stderr, "Error reading number of integers(first number) from file. Exiting.\n");
      exit(1);
  }
  
  // find minimum of numstoread and numintegers and use that as counttouse
      if(numsInFile &lt; numIntegers)
          countToUse = numsInFile;
      else
          countToUse = numIntegers;
  
  // Initialize the integers array with the minimum value as well - since it will only store this many
  integers = malloc(sizeof(int) * countToUse);
  
  for(int i = 0; i &lt; countToUse; i++){
      int currInt;
      if(fscanf(fp, "%d", &amp;currInt) == 1)
          integers[i] = currInt;
      else{
          fprintf(stderr, "Error loading integer array in countAndSort(). Exiting.\n");
          exit(1);
  }
  </code></pre>