但我在運行此程序時不斷收到此錯誤。我認爲這是因爲fgets功能。我嘗試初始化輸入變量爲NULL,看看是否會有所幫助,但事實並非如此。我也有一種預感,我可能需要malloc來解決問題。但你的幫助是高度讚賞。由於fgets導致的分段錯誤(核心轉儲) - 我認爲
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'和朋友分配的內存中使用'free'。您在這裏沒有分配任何內存。 –
@DavidBowling:'free'實際上是合法的,儘管缺少'malloc',因爲'NULL'可以安全地'免費',但它不是很有用。 – ShadowRanger
查看[fgets(3)'如何工作]手冊(https://linux.die.net/man/3/fgets)。將一個NULL指針傳遞給'fgets(3)'確實是錯誤的和意外的。作爲您未來工作的一般建議:*不要只是使用某些功能,而無需閱讀其文檔以瞭解它的工作原理。 – giusti