0

我是 C++ 的初学者,我已经为一些物理问题编写了这段代码,但是这段代码在运行时会非常快地消耗内存。基本思想是我希望函数 CCJJ 获取数组 x 和 I_noise 以及 A 一次,所以我不想逐个元素地喂它们。我不确定我是否以正确的方式管理数组。那么谁能告诉我消耗内存的东西在哪里,我该如何纠正呢?谢谢,

#include "CCJJDC_system.h"
double *sum_vector(double *a,double *b,double fact){
    double *result=new double[2*N];
    for(int i=0;i<2*N;i++)
        result[i]=a[i]+b[i]*fact;
    return result;
}

int main(){
    FILE *f;f=fopen("x.dat","w");
    double *x=new double[2*N], t, I_noise[N], I=0;
    //Matrix A as descrip in the paper
    //method to dinamicaly allocat the array 
    typedef double (A_t)[N];
    A_t *A = new A_t[N];
    //end of the method
    //auto A=new double[N][N];
    for(int i=0;i<N-1;i++){
        A[i][i] = 1.0 + 2.0*alpha;
        A[i+1][i] = -alpha;
        A[i][i+1] = -alpha;
    }
    A[N-1][N-1] = 1.0 + 2.0*alpha;
    A[0][N-1] = -alpha;
    A[N-1][0] = -alpha;
    //end of matrix A creation
    //Noise creation
    for(int i=0;i<N;i++)
        I_noise[i]=0;
    //Initinal condtion for \phi and V
    for(int i=0;i<2*N;i++)
        x[i]=0;

    double 
        t_max=500,
        t_min=0,
        h=0.1,
        *k1=new double[2*N],
        *k2=new double[2*N],
        *k3=new double[2*N],
        *k4=new double[2*N];
    double
        I_0=0.0,
        I_max=1.0,
        dI=0.001;   
    for(I=I_0;I<I_max;I+=dI){
        for(t=t_min;t<t_max;t=t+h){
            k1=CCJJDC(x,t,I_noise,I,A);
            k2=CCJJDC(sum_vector(x,k1,h/2),t,I_noise,I,A);
            k3=CCJJDC(sum_vector(x,k2,h/2),t,I_noise,I,A);
            k4=CCJJDC(sum_vector(x,k3,h),t,I_noise,I,A);
            for(int i=0;i<2*N;i++)
                x[i]=x[i]+(k1[i]+(2*k2[i])+(2*k3[i])+k4[i])*h/6;
        }
        double V=0;
        for(int i=0;i<N;i++)
            V+=x[i];
        std::cout<<"I: "<<I<<"\t V: "<<V<<std::endl;
        fprintf(f,"%f\t",I);
        fprintf(f,"%f\t",V);
        fprintf(f,"\n");
        fflush(f);
    }
    std::cout<<"finish"<<std::endl;
    fclose(f);
    return 0;
}

这是我的功能CCJJ

double *CCJJDC(double *x,double t,double *I_noise,double I,double (*A)[N]){
    double *xn;
    xn=x;
    //double
        //*result=new double[2*N],
        //I_noise[N],
        //x[2*N],
        //dx[2*N];
    for(int i=0;i<N;i++){
        for(int j=0;j<N;j++){
            x[j]+=A[i][j]*xn[j+N];
        }
        x[i+N]=I-sin(xn[i])-beta*x[i]+Amp*sin(Omega*t)+I_noise[i];
    }
    return x;
}
4

1 回答 1

1

您应该阅读有关内存分配的信息。每次您使用“新”时,您都在分配 C++ 中的内存,要求您释放自己(与 Java 等具有垃圾收集的语言相反):

http://en.wikipedia.org/wiki/Delete_(C%2B%2B)

于 2013-05-03T09:26:53.697 回答