C 使用“免费”时,下一个大小无效

C 使用“免费”时,下一个大小无效,c,malloc,realloc,C,Malloc,Realloc,另一种方法是复制 我有一个名为bond的结构,其定义如下: typedef struct{ int type1; int type2; int id_1; int id_2; float dist; } bond; 我在嵌套循环中分配这些结构的数组,并定期释放它。但是,由于某种原因,我得到了一个free()无效的下一个大小错误。代码如下: while(i<(C.num_type_A+C.num_type_B)){//1a bond_arr=

另一种方法是复制

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

typedef struct{
    int type1;
    int type2;
    int id_1;
    int id_2;
    float dist;
} bond;
我在嵌套循环中分配这些结构的数组,并定期释放它。但是,由于某种原因,我得到了一个free()无效的下一个大小错误。代码如下:

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

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

神圣嵌套蝙蝠侠!如果您在Linux上,请与Valgrind一起运行它以查找问题。您很可能在某个位置运行了数组的边界nd破坏了malloc的簿记信息。