此代码生成随机数,然后根据有关间隔的函数的输入生成直方图. “bins”表示直方图间隔,“bin_counts”表示给定间隔中的随机数.
我已经回顾了几个涉及类似问题的帖子,我知道我在某个地方的记忆中已经超出界限但是GBD只指向了“免费(箱子);”在代码的最后.我已经仔细检查了我的数组长度,我认为它们在不访问不存在的元素/写入未分配的内存方面都是正确的.奇怪的是代码按预期工作,它产生一个准确的直方图,现在我只需要帮助清理这个free()无效的下一个大小错误.如果有人有任何建议我会非常感激.整个输出是:
检测到glibc ./file:free():下一个大小无效(快):0x8429008
然后是内存中的一堆地址,由Backtrace和Memory Map分隔.
Backtrace只指向第129行,即“free(bins);”.提前致谢
#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 *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<=(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);
}
最佳答案
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;
}
您正在超越数组,为nbins双精度分配位置但写入nbins 1位置,并为bin_counts使用nbins位置但仅分配了nbins-1.