2012-01-31 49 views
4

此代码生成的随机数,然后产生基于输入到关于所述间隔的功能的直方图。 “容器”代表直方图区间,“bin_counts”代表给定区间内随机数的数量。glibc的检测到游离的():无效下一尺寸(快)

我查看了一些处理,有着相近的问题帖子,我明白,我出去在某处内存边界,但只GBD点我“自由(箱);”在代码的最后。我仔细检查了我的数组长度,我认为它们在不访问不存在的元素或写入未分配的内存方面都是正确的。奇怪的是,代码按预期工作,它产生一个准确的直方图,现在我只需要帮助清理这个免费()无效的下一个大小的错误。如果有人有任何建议,我会非常感激。整个输出是:

glibc的检测 ./file:免费():无效下一尺寸(快速):0x8429008

,随后在存储器中的一束的地址,通过回溯和存储器映射分隔。 Backtrace只指向129行,这是“免费(箱);”。在此先感谢

#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<=(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); 
     } 
+2

不要投的malloc'()的结果在'C. – 2012-01-31 01:10:33

+0

我看不出有什么问题,此代码的工作对我很好。你发送了整个功能吗? (顺便说一句,你为什么通过指针功能?) – asaelr 2012-01-31 01:14:54

+0

我走向你的意见,我很遗憾得到了同样的问题。 – 2012-01-31 01:16:08

回答

9
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的位置,并使用nbins地点为​​但只分配nbins-1

+0

WORD Daniel Fischer,谢谢你。 – 2012-01-31 01:58:32

+2

您可以使用[valgrind](http://valgrind.org/)等分析工具来检测这些事物。 – Coren 2012-01-31 14:14:51

+0

感谢您的信息,我一定会考虑valgrind。 – 2012-02-01 20:08:07

相关问题