2013-03-26 78 views
-2

或者,Facing an error — glibc detected free invalid next size (fast)的重複。使用免費時無效的下一個尺寸

我有如下定義的結構體稱爲鍵:

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

我分配這些結構的陣列中的嵌套循環,並定期釋放它。但是,出於某種原因,我得到一個免費的()無效的下一個大小的錯誤。代碼如下:

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 
+9

神聖的嵌套蝙蝠俠! – 2013-03-26 21:57:59

+2

如果您使用的是Linux,請使用Valgrind運行以發現問題。你很可能在某個地方跑過數組的邊界,並且拋棄了malloc的簿記信息。 – nneonneo 2013-03-26 21:59:28

回答

0

它看起來像realloc邏輯可能是責備。大小爲100的初始分配。然後在n達到nmax-1時生長。沒有顯示nmax的初始值(我看到)。即使它從100開始,它也不會在循環的頂部重置。因此,如果n有史以來增長超過100,並導致realloc,那麼nmax倍增,將不再匹配的原始大小100.

相關問題