title: Invalid Read size - Finding Command Line Average
body: <p>I'm trying to find the average of all the number added during command line execution. I'm getting some valgrind error of improoer memory allocation. </p>
  
  <pre><code>#include &lt;stdio.h&gt;
  #include &lt;stdlib.h&gt;
  #include &lt;string.h&gt;
  
  int * arg2int(int argc, const char* argv[]) {
      int i = 1;
      int *result = malloc (sizeof (int) * (argc-1));  
      for (i = 1; i &lt; argc; i++){
      result[i] = atoi(argv[i]);
      }
      return result;
  }
  
  float arrayAvg(int size, int *array) {
      /*STUB return 0.0/0.0; */
      int i = 0;
      float sum = 0.0f;
      for (i = 0; i &lt;= size; i++)
      sum = sum + array[i];
      int avg = sum/size;
      return (float)avg;
  }
  int main(int argc, const char* argv[]) {
      int *array = arg2int(argc, argv);
      float avg = arrayAvg(argc-1, array);
      printf("%.2f\n",avg);
      return 0;
  }
  </code></pre>
  
  <p>Here is the Valgrind error,</p>
  
  <pre><code>==785== Memcheck, a memory error detector
  ==785== Copyright (C) 2002-2013, and GNU GPL'd, by Julian Seward et al.
  ==785== Using Valgrind-3.10.1 and LibVEX; rerun with -h for copyright info
  ==785== Command: ./out
  ==785== 
  ==785== Invalid read of size 4
  </code></pre>
  
  <p>I analyzed that I'm reading from a constant character array of command line entries into an integer array. But how to remove the valgrind error.
  <strong>Quick Note</strong>
  The program will execute correctly without any errors. I have tested it. This is just about understanding why the valgrind error rises.</p>
  
  <p><strong>Sample Output:</strong></p>
  
  <pre><code>$ ./out 4 6 
  5.00
  </code></pre>