这是我的代码:
#include <stdio.h>
int main() {
FILE *file;
file = fopen("data.txt", "r");
int Array[10];
int i = 0;
fscanf(file, "%d", &i);
while (!feof(file)) {
fArray[j] = i;
j++;
fscanf(file, "%d", &i);
}
fclose(file);
return 0;
}
当我在Windows上运行它时,它工作正常,但是当我尝试在Mac上运行它时,我得到了一个分段错误:11。
data.txt文件与我的test.c文件在同一个文件夹中,上面显示了代码。
我试图找出分段错误发生的位置,而且是在我调用fscanf()时。
答案 0 :(得分:1)
在一个小例子中有太多潜在的失败:
#include <stdio.h>
int main() {
FILE *file;
file = fopen("data.txt", "r");
/* FAIL 1 - what if file is NULL? */
int Array[10];
/* fail 2 - bad naming convention - variables typically start with lower case (note: that's a lower case fail ;-)
fail 3 magic number 10 for array size
*/
int i = 0;
fscanf(file, "%d", &i);
/* FAIL 4 - see iharob's comment on the question. I didn't pick this one up */
while (!feof(file)) {
/* FAIL 5 - compilation failure. What is j? - what is fArray?
(I'm assuming j is initialized, but since we don't know what it is...)
FAIL 6 How do we know there isn't an array out of bounds access here
(as in j goes past the end of fArray) */
fArray[j] = i;
j++;
/* FAIL 7 - if the file contains something other than an int then
fscanf will return early and so you'll never hit EOF.
Credit for this one goes to rpattiso
fail 8 (lowercase) - due of the feof style issue, you have to
repeat the fscan line - once outside the loop and once inside.
*/
fscanf(file, "%d", &i);
}
fclose(file);
return 0;
}