4

我正在开发 Visual Studio 2010。该程序本身最初是为 CUDA 的未来端口而设计的,所以一切都准备好了,但现在我只是在测试它是否适用于纯 c++(实际上我'我现在尝试坚持使用 c,因为我更熟悉它)。

相关代码为:

#define NMBR_EXP_ENERGIES 21
#define NMBR_Ls 3
#define NMBR_POINTS 20000

<Emin, Emax, dE are initialized as global constants>
int NMBR_EXP_ENERGIES_L[NMBR_Ls];

<Some functions>

void write_results(double ** u, int * NmbrNodes, int * div){
const char prefix[] = "wave_function_";
char filename[24];
double *eigenergies;
int div0,i,j,k,l,m;
FILE *file_u;
FILE *file_output;

eigenergies = (double *)malloc(NMBR_EXP_ENERGIES*sizeof(double));
j=0;
m=0;
file_output = fopen("computation_results.out","w");
fprintf(file_output,"This file contains  the output\n");


for(l=0;l<NMBR_Ls;l++){
    div0=div[l*NMBR_ENERGIES];
    for(i = l*NMBR_ENERGIES;i<NMBR_ENERGIES*(l+1);i++){
        if (div[i] != div0 && m<NMBR_EXP_ENERGIES_L[l]){
            div0=div[i];
            j++;
            m++;
            eigenergies[j-1] = (Emin+((double) (i-l*NMBR_ENERGIES))*dE)-dE/2.0;
            fprintf(file_output,"The eigenergy %d is %1.15lf and the wavefunction has %d nodes\n",j,eigenergies[j-1],NmbrNodes[i]);
            sprintf(filename,"%d_%s%d.out",l,prefix,j);
            file_u = fopen(filename,"w");
            for(k=0;k<NMBR_POINTS;k++){
                fprintf(file_u,"%lf %1.15lf \n",k*RMAX/NMBR_POINTS,u[i][k]);
            }
            fclose(file_u);
        }
    }
    if (j < NMBR_EXP_ENERGIES_L[l]){
        j = NMBR_EXP_ENERGIES_L[l];
    }
    m=0;
    }
fprintf(file_output,"R = %1.15lf\n ",error_control(eigenergies));
fprintf(file_output,"%d eigenergies were found\nIts eigenfunctions were stored on the file %sj.out, 1<j<%d",j,prefix,j);
fclose(file_output);
free(eigenergies);
}

<Some functions>

int main(void){

<Code that executes the computation and stores it on u[i][j],NmbrNodes[i] and div[i]>

write_results(u, NmbrNodes, div);

}

向量 div 之前根据需要填充了 1 和 -1。当 l = 0 和 l = 1 时,程序运行良好。但是,当他最后一次启动外循环(l = 2)并第二次进入 if 时,它在 line 上崩溃fprintf(file_output,"The eigenergy %d is %1.15lf and the wavefunction has %d nodes\n",j,eigenergies[j-1],NmbrNodes[i]);。错误信息是

First-chance exception at 0x77dd3ea0 in Potential_Model_Numerov.exe: 0xC0000005: Access violation writing location 0x00000014.
Unhandled exception at 0x77dd3ea0 in Potential_Model_Numerov.exe: 0xC0000005: Access violation writing location 0x00000014.

选择打破程序时,它会在功能末尾打开mlock.c文件void __cdecl _lock

我已经检查过我没有读取超出其分配空间的任何向量(eigenergies 一直持续到 eigenergies[20] 和 j =17,当这种情况发生时 NmbrNodes 一直持续到 NmbrNodes[3071] 和 i = 3009碰撞)。所以我不知道他为什么要读取一个被禁止的内存地址。有人有什么主意吗?

谢谢!

旁注:我有另一个功能基本相同,但没有向硬盘驱动器写入任何内容,而且这个功能运行良好。此外,有时它会打开文件 osfinfo.c 而不是 mlock.c 并在函数结束时停止int __cdecl __lock_fhandle

4

1 回答 1

1

你确定eigenenergies不是NULL吗?您永远不会检查malloc().

鉴于您在地址 0x00000014 处遇到访问冲突,并且您声称

eigenergies 一直到 eigenergies[20]

那将是我的第一个猜测。请注意,0x14等于20

您可能想跳过malloc()ing 并使用double eigenenergies[NMBR_EXP_ENERGIES].

于 2013-09-16T03:33:01.783 回答