1

I'm working on Mac OSX, and using bash in terminal. The machine has 8GB of RAM. I don't know why I am getting a segment fault 11 for this code. From my three weeks of experience, I usually get them form having too much memory being requested. But I am only asking for 5, 200 entry arrays. Does this have something to do with opening and reading text files?

What could to make the program run, as is? Is malloc relevant to this? Thanks for any help you can offer.

#include <stdio.h>
#include <math.h>

int main(){
double Mj[200]={0};
double Ma[200]={0};
double Cj[200]={0};
double Ca[200]={0};
double index[200]={0};

FILE *Matlab;
Matlab = fopen("TestbedComp.txt","r");
FILE *Cprog;
Cprog = fopen("results.txt","r");

int j = 0;
while( fscanf(Matlab,"%lf, %lf, %lf", &index[j], &Mj[j], &Ma[j]) == 3 ){
    printf("%lf, %lf, %lf\n", index[j], Mj[j], Ma[j]);
    j++;
}

fclose(Matlab);
printf("\n");

j = 0;
while( fscanf(Cprog,"%lf, %lf, %lf", &index[j], &Cj[j], &Ca[j]) == 3 ){
    printf("%lf, %lf, %lf\n", index[j], Cj[j], Ca[j]);
    j++;
}

fclose(Cprog);

double pej[200]={0};
for (j=0; j<200; j++) {
    pej[j] = fabs(Mj[j]-Cj[j])/Mj[j];
}

double pea[200]={0};
for (j=0; j<200; j++) {
    pea[j] = fabs(Ma[j]-Ca[j])/Ma[j];
}

FILE *out;
out = fopen("PercentError.txt","w");

for (j=0; j<200; j++) {
    fprintf(out,"%.15lf, %.15lf, %.15lf \n", index[j], pej[j], pea[j]);
}

fclose(out);

return 0;
}
4

2 回答 2

1

fscanf一直读到行尾。如果代码中没有行,它会尝试完整地读取它,并且您可能会遇到分段错误。

你能提供你试图阅读的文件的例子吗?

于 2013-06-03T19:24:49.930 回答
1

我敢打赌你真的在函数序言中崩溃了...... 1000 双打立即从你的堆栈中取出 16000 个字节。尝试calloc使用那些而不是使用堆栈分配。

于 2013-06-03T19:28:16.150 回答