我正在尝试读取一个整数文件,其中包含文件中的整数个数作为第一个整数,但是当我在读取文件后尝试关闭该文件时,出现了段错误。
我读到,如果文件指针为空并且您尝试关闭它,则会出现段错误。但是,我在关闭它之前检查它是否为空,它不为空,并且仍然给我一个段错误..
我通过 GDB 运行它,一旦 fclose(fp) 执行,它就会出现段错误。
这是怎么回事?
这是我的代码:
char *mode = "r";
int numsToRead = 0;
FILE *fp = fopen(inputFile, mode);
if (fp == NULL){
fprintf(stderr, "Can't open input file!\n");
exit(1);
}
int *temp;
int index = 0;
// Get number of integers (first integer)
fscanf(fp, "%d", &numsToRead);
fprintf(stdout, "nums to read: %d\n", numsToRead);
integers = (int*)malloc(sizeof(int) * numsToRead);
for(int i = 0; i <= numsToRead; i++){
int currInt;
if(fscanf(fp, "%d", &currInt) == 1)
integers[i] = currInt;
else
break;
}
if(fp != NULL)
fclose(fp);
最佳答案
for(int i = 0; i <= numsToRead; i++)
// ^^
应该是
for(int i = 0; i < numsToRead; i++)
// ^
关于c - fclose 上的段错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28445528/