title: glibc detected free(): invalid next size (fast)
body: <p>This code generates random numbers and then produces a histogram based on input to the functions regarding the intervals. "bins" represents the histogram intervals and "bin_counts" holds the number of random numbers in a given interval.</p>
  
  <p>I've reviewed several of the posts dealing with similiar issues and I understand that I'm out of bounds in the memory somewhere but GBD only points me to the "free(bins);" at the end of the code. I've double-checked my array lengths and I think they are all correct in terms of not accessing elements that don't exist/writing to memory not allocated. The weird thing is that the code works as intended, it produces an accuarate histogram, now I just need helping cleaning up this free() invalid next size error. If anybody has any suggestions I would be much obliged. The whole output is : </p>
  
  <p><strong>glibc detected</strong> ./file: free(): invalid next size (fast): 0x8429008</p>
  
  <p>followed by a bunch of addresses in memory, seperated by Backtrace and Memory Map.
  The Backtrace only points me towards line 129, which is "free(bins);". Thanks in advance</p>
  
  <pre><code>    #include "stdio.h"
      #include "string.h"
      #include "stdlib.h"
  
      void histo(int N, double m, double M, int nbins, int *bin_counts, double *bins);
  
       int main(int argc, char* argv[])
       {
  
       int *ptr_bin_counts;
       double *ptr_bins; 
  
       histo(5,0.0,11.0,4, ptr_bin_counts, ptr_bins);
  
       return 0;
       } 
  
       void histo(int N, double m, double M, int nbins, int *bin_counts, double *bins)
       {
  
       srand(time(NULL));
       int i,j,k,x,y;
       double interval;
       int randoms[N-1];
       int temp_M = (int)M;
       int temp_m = (int)m;
       interval = (M-m) /((double)nbins);
  
  
       //allocating mem to arrays
       bins =(double*)malloc(nbins * sizeof(double));
       bin_counts =(int*)malloc((nbins-1) * sizeof(int));
  
       //create bins from intervals
       for(j=0; j&lt;=(nbins); j++)
       {
              bins[j] = m + (j*interval); 
       } 
  
        //generate "bin_counts[]" with all 0's
        for(y=0; y&lt;=(nbins-1); y++)
         {
           bin_counts[y] = 0; 
         }
  
  
        //Generate "N" random numbers in "randoms[]" array
        for(k =0; k&lt;=(N-1); k++)
        {
            randoms[k] = rand() % (temp_M + temp_m);
            printf("The random number is %d \n", randoms[k]);
        }
  
         //histogram code 
         for(i=0; i&lt;=(N-1); i++)
          {
           for(x=0; x&lt;=(nbins-1); x++)
           {
                if( (double)randoms[i]&lt;=bins[x+1] &amp;&amp; (double)randoms[i]&gt;=bins[x] )
                 {
                      bin_counts[x] = bin_counts[x] + 1; 
                 }
           }
           }
           free(bins);
           free(bin_counts);
           }
  </code></pre>