I was trying to get a mathematical result but I kept on getting a segmentation fault, the segmentation fault occurs at the “cout” line. I don’t think anything is wrong in the r[] array or the LJ[] array.
for (k = 0; k < 15; k++)
{
for (i = 0; i < 15; i++)
{
if (i == k)
{
NULL;
}
else
{
//Use the 3D distance formula
term1 = fabs(x[k] - x[i]);
term1 = pow(term1, 2);
term2 = fabs(y[k] - z[i]);
term2 = pow(term2, 2);
term3 = fabs(z[k] - z[i]);
term3 = pow(term3, 2);
result = term1 + term2 + term3;
result = sqrt(result);
r[h] = result; //Store the result in an array
h++;
}
}
}
//Calculate Lennard-Jones potential of every pair
for(itr = 0; itr < 210; itr++)
{
term1 = pow(r[itr], 12);
term1 = 1/term1;
term2 = pow(r[itr], 6);
term2 = 2/term2;
LJ[itr] = term1 - term2;
}
double Ei;
for(itr = 0; itr < 210; itr++)
{
Ei = LJ[itr] + Ei;
}
Ei = Ei/2;
cout << "The new Energy level " << Ei << endl;
Update: you have updated the definition of LJ, so this is no longer the issue.
Since this is c++, why are you using loop and indexing? a better (as in: a safer) solution would be to use the standard library algorithms and in particular accumulate.
By doing this you would gain in clarity and possibly remove the source of the segfault.
Unless other requirements are constraining you, you should follow Scott Meyer’s advice of favoring algorithms over loops.
Second Update, with the whole code available: You must make sure that you are only accessing memory locations which you correctly allocated. So:
Better yet, remove all those magic numbers, instead of 210 use k_max * (j_max – 1) and define
Use a std::vector instead of an array, this will take care of memory allocation for you.
Printing the values of h and itr (or using a debugger, which is a very useful tool) will show you where you are accessing memory which you didn’t reserve.