【问题标题】:invalid next size when using free [closed]使用免费时无效的下一个尺寸[关闭]
【发布时间】:2013-03-26 21:56:57
【问题描述】:

或者,Facing an error — glibc detected free invalid next size (fast) 的副本。

我有一个名为 bond 的结构体,其定义如下:

typedef struct{
    int type1;
    int type2;
    int id_1;
    int id_2;
    float dist;
} bond;

我在嵌套循环中分配这些结构的数组并定期释放它。但是,由于某种原因,我收到了 free() Invalid Next size 错误。代码如下:

while(i<(C.num_type_A+C.num_type_B)){//1a
    bond_arr=(bond*)malloc(100*sizeof(bond));

    a=-N1;
    while(a<=N1){//2a

        b=-N2;
        while(b<=N2){//3a

            c=-N3;
            while(c<=N3){//4a

                j=0;
                while(j<(C.num_type_A+C.num_type_B)){//5a

                    //if the same atom do nothing
                    if((i==j)&&(a==0)&&(b==0)&&(c==0)){//6a
                        j=j+1;
                    }//6b
                    else{//7a

                        //calculate bond length
                        bondlength=calc_dist(a,b,c,i,j,C);

                        if(bondlength<=cutoff){//8a
                            //store bond
                            temp_bond.type1=((i+1)<=C.num_type_A);
                            temp_bond.type2=((j+1)<=C.num_type_B);
                            temp_bond.id_1=i;
                            temp_bond.id_2=j;
                            temp_bond.dist=bondlength;
                            bond_arr[n]=temp_bond;
                            n=n+1;

                            //if out of memory allocate twice as much
                            if(n==(nmax-1)){//9a
                                printf("begin\n");
                                temp_ptr=realloc(bond_arr,sizeof(bond)*2*nmax);
                                printf("end\n");

                                if(temp_ptr==NULL){
                                    printf("Memory allocation failed\n");
                                }
                                else{
                                    bond_arr=temp_ptr;
                                }
                                nmax=2*nmax;
                            }//9b
                        }//8b
                    }//7b
                    j=j+1;
                }//5b
                c=c+1;
            }//4b
            b=b+1;
        }//3b
        a=a+1;
    }//2b

    //sort bonds and update LI index
    sort_bonds(bond_arr,n);
    f=update_LI(bond_arr,LIcurr,n);
    LIcurr=f;
    printf("%d\n",n);
    free(bond_arr);
    n=0;
    i=i+1;
}//1b

【问题讨论】:

  • 圣巢蝙蝠侠!
  • 如果您使用的是 Linux,请使用 Valgrind 运行它以找出问题所在。您很可能在某个地方越过了数组的边界并丢弃了 malloc 的簿记信息。

标签: c malloc realloc


【解决方案1】:

看起来 realloc 逻辑可能是罪魁祸首。初始分配大小为 100。然后当n 达到nmax-1 时增长。 nmax 的初始值没有显示(我看到了)。即使它从 100 开始,它也不会在循环顶部重置。因此,如果n 增长到超过 100 并导致重新分配,则 nmax 会翻倍,并且不再匹配原始大小 100。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多