Glibc detected free (): invalid next size (fast)

This code generates random numbers and then creates a histogram based on input of functions related to intervals. "bins" represent histogram intervals, and "bin_counts" contains the number of random numbers in a given interval.

I looked through a few posts devoted to similar problems, and I understand that I am somewhere outside the limits of memory, but GBD indicates only "free (bunkers)"; at the end of the code. I double-checked the length of the array, and I think that they are all correct in terms of lack of access to elements that do not exist / are written to memory that is not allocated. The strange thing is that the code works as intended, it produces a neat histogram, now I just need to help clear this free () invalid error of the next size. If anyone has any suggestions, I would be very obliged. All conclusion:

glibc ./file detected: free (): invalid next size (fast): 0x8429008

followed by a bunch of addresses in memory, separated by Backtrace and Map Memory. Backtrace only points to line 129, which is "free (bunkers)." thanks in advance

#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 = (Mm) /((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<=(nbins); j++) { bins[j] = m + (j*interval); } //generate "bin_counts[]" with all 0's for(y=0; y<=(nbins-1); y++) { bin_counts[y] = 0; } //Generate "N" random numbers in "randoms[]" array for(k =0; k<=(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<=(N-1); i++) { for(x=0; x<=(nbins-1); x++) { if( (double)randoms[i]<=bins[x+1] && (double)randoms[i]>=bins[x] ) { bin_counts[x] = bin_counts[x] + 1; } } } free(bins); free(bin_counts); } 
+4
source share
1 answer
 bins =(double*)malloc(nbins * sizeof(double)); bin_counts =(int*)malloc((nbins-1) * sizeof(int)); //create bins from intervals for(j=0; j<=(nbins); j++) { bins[j] = m + (j*interval); } //generate "bin_counts[]" with all 0's for(y=0; y<=(nbins-1); y++) { bin_counts[y] = 0; } 

You step over your arrays, you allocate space for nbins double, but write to nbins+1 locations and use nbins locations for bin_counts , but only allocate nbins-1 .

+9
source

Source: https://habr.com/ru/post/1393874/


All Articles