c - invalid next size when using free -


alternatively, duplicate of facing error — glibc detected free invalid next size (fast).

i have struct called bond defined follows:

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

i allocating array of these structs in nested loop , freeing periodically. however, reason getting free() invalid next size error. code below:

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 same atom 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                             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 , 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 

it looks realloc logic might blame. initial allocation of size 100. grown when n reaches nmax-1. initial value of nmax not shown (that see). if starts @ 100, not reset @ top of loop. if n ever grows past 100 , causes realloc, nmax doubled , no longer match original size of 100.


Comments