但是当我运行该程序时,我不断收到此错误。我认为这是因为 fgets 函数。我尝试将输入变量初始化为 NULL 以查看是否有帮助,但没有。我也有预感,我可能需要 malloc 来解决问题。但我们非常感谢您的帮助。
int main(int argc, char* argv[])
{
char* input = NULL;
// ensure one and only one command line argument
if (argc != 2)
{
printf("Usage: %s [name of document]\n", argv[0]);
return 1;
}
// open a new document for writing
FILE* fp = fopen(argv[1], "w");
// check for successful open
if(fp == NULL)
{
printf("Could not create %s\n", argv[1]);
return 2;
}
// get text from user and save to file
while(true)
{
// get text from user
printf("Enter a new line of text (or \"quit\"):\n");
fgets(input, 50, stdin);
// if user wants to quit
if (input != NULL && strcmp(input, "quit") == 0)
{
free(input);
break;
}
// if user wants to enter text
else if (input != NULL)
{
fputs(input, fp);
fputs("\n", fp);
printf("CHA-CHING!\n\n");
free(input);
}
}
// close the file and end successfuly
fclose(fp);
return 0;
}
最佳答案
你从来没有malloc
-edinput
,所以是的,fgets
正在取消引用NULL
指针作为其缓冲区,那将会消亡。要么将 input
更改为堆栈数组(并删除它的 free
),要么实际调用 malloc
来分配内存,以便 input
code> 未指向 NULL
。
关于c - 由于 fgets 导致段错误(核心转储) - 我认为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41436265/