I have the following code is code snippet of large code. I am trying to free an array of structures for which I have allocated memory in this code. Unfortunately I get either a seg fault or no segfault (error free) when I change specific line in the code. I am not able to find the reason why. Can somebody please have a look and point out the reason. So If I change atom[i]->natoms to atom[i]->natoms-1 in void_free_atom I get no segault but valgrind shows that heap is not completely free. Note atom[i]->natoms is a constant number.
#include "stdheader.h"
#include "Atom.h"
Atom **atominfo(FILE *fp1,size_t nbytes,char *my_string,Ljcoeff *lj, int natoms) {
int i;
Atom **atom=(Atom **) malloc(sizeof(Atom *)*natoms);
// printf("%d\n",natoms);
for (i = 0; i < natoms; i++) {
atom[i]=(Atom *) malloc(sizeof(Atom));
atom[i]->natoms=natoms;
atom[i]->eps=lj->eps[i];
atom[i]->sigma=lj->sigma[i];
getline(&my_string, &nbytes, fp1);
sscanf(my_string, "%d %*d %lf %lf %lf %lf\n", &atom[i]->id, &atom[i]->x,
&atom[i]->y, &atom[i]->z, &atom[i]->q);
// printf("%d %d %lf %lf %lf %lf\n",i+1,atom[i]->id,atom[i]->x,atom[i]->y,atom[i]->z,atom[i]->q);
}
return atom;
}
void free_atom(Atom **atom)
{
int i;
for(i=0;i< atom[i]->natoms;i++){
//printf("%d\n",atom[i]->natoms-1);
free(atom[i]);
}
free(atom);
}