-2

或者,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
4

1 回答 1

0

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

于 2013-03-26T22:04:24.703 回答