c - 由于 fgets 导致段错误(核心转储) - 我认为

标签 c

但是当我运行该程序时,我不断收到此错误。我认为这是因为 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/

上一篇:C 编程模式

下一篇:c - 指针重定义错误

相关文章:

c - 如何动态计算动态分配内存的大小

c - 具有多个语句的三元运算符

c - 将两个以上的 "struct"写入文件的问题,然后读取文件

c - 字节中的位反转如何工作?

c - 循环编辑控件

c - 写入 .bmp 文件时的字节移位

在像 printf() 这样的可变参数函数中,整数提升能否以相反的顺序发生(例如 long int 到 int)?

c - char 到 int 转换输出背后的原因是什么?

c++ - 如何在 C 中使用 printf() 格式化在 double 前面保留空格

c - 如何将一个元素移动到固定数组的左侧