我对 C 编程相当陌生,并试图正确理解 C 中内存管理的来龙去脉。
我制作了一个简单的程序,可以毫无问题地进行编译,但是在调试时在 printf("The next line gets aegmentation error"); 行之后给了我一个分段错误
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h> //Here you have the isdigit fun
int main()
{
FILE* filePtr;
char fileStr[150]; // Buffer for reading file.
filePtr = fopen("ManyRandomNumbersLog.txt","r");
printf("\n\nNow reading the file:\n");
while(!feof(filePtr))
{
printf("The next line is a segmentation fault!\n");
// WHYYYY?!?!?!?
fgets(fileStr, 150, filePtr);
printf("%s\n",fileStr);
}
return 0;
}
fgets 函数调用似乎给出了此错误,因为指针有以下“错误?”里面:您知道问题是什么以及如何预防吗?
我尝试调试它,但无法弄清楚为什么指针无法访问该内存。
而且feof
并不像你想象的那样工作。
int main()
{
FILE* filePtr;
char fileStr[150]; // Buffer for reading file.
filePtr = fopen("ManyRandomNumbersLog.txt","r");
printf("\n\nNow reading the file:\n");
if(filePtr)
{
while(fgets(fileStr, 150, filePtr))
{
printf("%s\n",fileStr);
//filestr will also contain '\n' at the end if it was present in the file.
}
fclose(filePtr);
}
return 0;
}