遇到问题:在函数中开辟动态内存(已解决)
我定义了一个类,类中有指针成员,有函数,有的函数给这些指针成员开辟动态内存,有的函数引用这些动态内存的数据,有的函数释放这些动态内存,结果运行起来发现不可行。
class eigeninfo{
public:
int num_eig;
int *eig_J;
int *eig_pr;
int *eig_u;
int *eig_i;
double *eig;
void read(char *file_eig){
cout<<"1"<<endl;
FILE *fp;
if((fp=fopen(file_eig, "r"))==NULL)
cout<<"error: failed to open "<<file_eig<<endl;
char temps[temps_scale];
char tempchar;
int num_Jpi;
fscanf(fp,"%d",&num_Jpi);
cout<<"num_Jpi="<<num_Jpi<<endl;
// skip J, parity, Jpi_dim, calculate Jpi_Border
for(int i=0;i<num_Jpi+2;i++){
fscanf(fp,"%[^\n]%*c",temps);
}
cout<<"2"<<endl;
// skip proton basises
int num_basis_p;
fscanf(fp,"%d",&num_basis_p);
for(int i=0;i<num_basis_p+2;i++){
fscanf(fp,"%[^\n]%*c",temps);
}
// skip neutron basises
int num_basis_n;
fscanf(fp,"%d",&num_basis_n);
for(int i=0;i<num_basis_n+2;i++){
fscanf(fp,"%[^\n]%*c",temps);
}
cout<<"3"<<endl;
// start reading what it wants
fscanf(fp,"%d",&num_eig);
//open memory for eig_J, eig_pr, eig_u, eig_i, eig
int *eig_J=new int [num_eig];
int *eig_pr=new int [num_eig];
int *eig_u=new int [num_eig];
int *eig_i=new int [num_eig];
double *eig=new double [num_eig];
for(int i=0;i<2;i++){
fscanf(fp,"%[^\n]%*c",temps);
}
for(int i=0;i<num_eig;i++){
fscanf(fp, "%d\t%d\t%d\t%d\t%lf",
&eig_J[i],
&eig_pr[i],
&eig_u[i],
&eig_i[i],
&eig[i]);
}
fclose(fp);
};
void print(char *file_eig){
cout<<"Read from "<<file_eig<<":";
cout<<"num_eig="<<num_eig<<endl;
cout<<"eig\tJ\tparity\tu\ti\teigwave\n";
for(int k=0;k<num_eig;k++){
cout<<"k="<<k<<endl;
cout<<eig_J[k]<<"\t";
cout<<eig_pr[k]<<"\t";
cout<<eig_u[k]<<"\t";
cout<<eig_i[k]<<"\t";
cout<<eig[k]<<"\n";
cout<<"\t";
}
cout<<endl;
};
void deletememory(){
delete [] eig_J;
delete [] eig_pr;
delete [] eig_u;
delete [] eig_i;
delete [] eig;
};
};
然后写了一个测试文件来测试它,调用 eigeninfo.read(), eigeninfo.print(), eigeninfo.deletememory()
结果在执行eigeninfo.print()时出现了:Segmentation fault (core dumped)
如果在一个函数中开辟动态内存,就在这个函数中引用和释放,到目前为止我发现,如果遵循这个原则就不会出错。
============================================================================================
2019/5/20 更
其实是因为代码里有错误, int * eig_J = new int [num_eig] ... 改为 eig_J = new int [num_eig] ... 就运行通过了