2013-03-26 1 views
-2

Facing an error — glibc detected free invalid next size (fast)의 사본.무료 사용시 다음 크기가 유효하지 않음

I는 다음과 같이 정의되는 구조체라는 결합 가지고

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

Holy Nesting Batman! –

+2

Linux를 사용하는 경우 Valgrind와 함께 실행하여 문제를 찾으십시오. 당신은 어딘가 배열의 범위를 돌연히 돌았을 것이며'malloc'의 부기 정보를 파기했을 것입니다. – nneonneo

답변

0

realloc 논리가 문제가있는 것 같습니다. 초기 크기는 100입니다. nnmax-1에 도달하면 자랍니다. nmax의 초기 값은 표시되지 않습니다. 100에서 시작하더라도 루프 상단에서 재설정되지 않습니다. 따라서 n이 100 이상으로 커지고 재 할당이 발생하면 nmax가 배가되어 더 이상 원래 크기 인 100과 일치하지 않게됩니다.

관련 문제