I print the value that I'm returning right before my return statement, and tell my code to print the value that was returned right after the function call. However, I get a segmentation fault after my first print statement and before my second (also interesting to note, this always happens on the third time the function is called; never the first or the second, never fourth or later). I tried printing out all of the data that I'm working on to see if the rest of my code was doing something it maybe shouldn't, but my data up to that point looks fine. Here's the function:
int findHydrogen(struct Amino* amino, int nPos, float* diff, int totRead) {
struct Atom* atoms;
int* bonds;
int numBonds;
int i;
int retVal;
int numAtoms;
numAtoms = (*amino).numAtoms;
atoms = (struct Atom *) malloc(sizeof(struct Atom) * numAtoms);
atoms = (*amino).atoms;
numBonds = atoms[nPos].numBonds;
bonds = (int *) malloc(sizeof(int) * numBonds);
bonds = atoms[nPos].bonds;
for(i = 0; i < (*amino).numAtoms; i++)
printf("ATOM\t\t%d %s\t0001\t%f\t%f\t%f\n", i + 1, atoms[i].type, atoms[i].x, atoms[i].y, atoms[i].z);
for(i = 0; i < numBonds; i++)
if(atoms[bonds[i] - totRead].type[0] == 'H') {
diff[0] = atoms[bonds[i] - totRead].x - atoms[nPos].x;
diff[1] = atoms[bonds[i] - totRead].y - atoms[nPos].y;
diff[2] = atoms[bonds[i] - totRead].z - atoms[nPos].z;
retVal = bonds[i] - totRead;
bonds = (int *) malloc(sizeof(int));
free(bonds);
atoms = (struct Atom *) malloc(sizeof(struct Atom));
free(atoms);
printf("2 %d\n", retVal);
return retVal;
}
}
As I mentioned before, it works fine the first two times I run it, the third time it prints the correct value of retVal, then seg faults somewhere before it gets to where I called the function, which I do as:
hPos = findHydrogen((&aminoAcid[i]), nPos, diff, totRead);
printf("%d\n", hPos);