cant find out why valgrind gives errors in my code which has array of structures : <p>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. </p>

<pre><code>#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 &lt; natoms; i++) {
                                        atom[i]=(Atom *) malloc(sizeof(Atom));
                                        atom[i]-&gt;natoms=natoms;
                                        atom[i]-&gt;eps=lj-&gt;eps[i];
                                        atom[i]-&gt;sigma=lj-&gt;sigma[i];      
                    getline(&amp;my_string, &amp;nbytes, fp1);
                    sscanf(my_string, "%d %*d %lf %lf %lf %lf\n",  &amp;atom[i]-&gt;id, &amp;atom[i]-&gt;x,
                            &amp;atom[i]-&gt;y, &amp;atom[i]-&gt;z, &amp;atom[i]-&gt;q);
//                                      printf("%d %d %lf %lf %lf %lf\n",i+1,atom[i]-&gt;id,atom[i]-&gt;x,atom[i]-&gt;y,atom[i]-&gt;z,atom[i]-&gt;q);
                }                              
                return atom;


}





void free_atom(Atom **atom)
{
int i;
for(i=0;i&lt; atom[i]-&gt;natoms;i++){
//printf("%d\n",atom[i]-&gt;natoms-1);
free(atom[i]);
}
free(atom);
}
</code></pre>
