我有一个函数,该函数返回指向双精度数组的指针:
double * centerOfMass(System &system) {
long unsigned int size = system.atoms.size();
double x_mass_sum=0.0; double y_mass_sum=0.0; double z_mass_sum=0.0; double mass_sum=0.0;
for (int i=0; i<=size; i++) {
double atom_mass = system.atoms[i].m;
mass_sum += atom_mass;
x_mass_sum += system.atoms[i].pos["x"]*atom_mass;
y_mass_sum += system.atoms[i].pos["y"]*atom_mass;
z_mass_sum += system.atoms[i].pos["z"]*atom_mass;
}
double comx = x_mass_sum/mass_sum;
double comy = y_mass_sum/mass_sum;
double comz = z_mass_sum/mass_sum;
double* output = new double[3]; // <-------- here is output
output[0] = comx*1e10; // convert all to A for writing xyz
output[1] = comy*1e10;
output[2] = comz*1e10;
return output;
}
当我尝试通过将数组保存到变量中(在另一个函数中)来访问输出时,程序运行时会出现分段错误(但编译正常):
void writeXYZ(System &system, string filename, int step) {
ofstream myfile;
myfile.open (filename, ios_base::app);
long unsigned int size = system.atoms.size();
myfile << to_string(size) + "\nStep count: " + to_string(step) + "\n";
for (int i = 0; i < size; i++) {
myfile << system.atoms[i].name;
myfile << " ";
myfile << system.atoms[i].pos["x"]*1e10;
myfile << " ";
myfile << system.atoms[i].pos["y"]*1e10;
myfile << " ";
myfile << system.atoms[i].pos["z"]*1e10;
myfile << "\n";
}
// get center of mass
double* comfinal = new double[3]; // goes fine
comfinal = centerOfMass(system); // does NOT go fine..
myfile << "COM " << to_string(comfinal[0]) << " " << to_string(comfinal[1]) << " " << to_string(comfinal[2]) << "\n";
myfile.close();
}
运行程序时,功能正常,直到尝试调用
centerOfMass
函数。我已经检查了大多数可能的解决方案,我认为我缺乏对C ++中指针及其作用域的理解。我精通PHP,因此处理内存显式地是有问题的。谢谢你。
for (int i=0; i<=size; i++) {
看起来很奇怪。难道不应该是for (int i=0; i<size; i++) {
吗?system.atoms
的类型是什么? - songyuanyaocomfinal
:double* comfinal = new double[3];
,然后在这一行中重新分配了指针:comfinal = centerOfMass(system);
当你执行第二次赋值时,你泄漏了你在第一次调用 new 时分配的内存。最后,在程序结束时,你没有调用comfinal
上的 delete,因此泄漏了它在程序结束时所持有的内存。 - Alex Zywickidouble* comfinal = centerOfMass(system);
,然后在writeXYZ
的末尾添加delete[] comfinal
。 - Alex Zywicki