Alternatively, duplicate of Facing an error — glibc detected free invalid next size (fast).
I have a struct called bond which is defined as follows:
typedef struct{
int type1;
int type2;
int id_1;
int id_2;
float dist;
} bond;
I am allocating an array of these structs in a nested loop and freeing it periodically. However, for some reason I am getting a free() Invalid Next size error. The code is 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 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
It looks like the realloc logic might be to blame. The initial allocation of size 100. Then it is grown when n
reaches nmax-1
. The initial value of nmax
is not shown (that I see). Even if it starts at 100, it is not reset at the top of the loop. So if n
ever grows past 100 and causes a realloc, then nmax is doubled and would no longer match the original size of 100.