繁体   English   中英

fgets() 问题和外部文件最后一行的分段错误

[英]Having an issues with fgets() and segmentation faults on last line of external file

这是我程序中的一段代码,它导致最后一行出现分段错误。 我的程序应该从文件(如果用户指定)或从控制台的手动输入中获取输入。 当用户通过控制台输入句子时,它就起作用了。 但是,当我从外部文件中取出句子时,我在最后一行(将到达 EOF 完成的行)出现分段错误。 假设文件已关闭,并且在此代码段之外释放了内存

这是片段:

if(inputExists == 1) {
        char *input = malloc(256);
        ip = fopen(inFile, "r");
        if(ip) {
            while(fgets(input, 256, ip) != NULL) {
                printf("%s", input);
            }
        }
    }

这是外部文件中的内容:

bob is working.
david is a new hire.
alice is bob's boss.
charles doesn't like bob.

这是我在完整程序时得到的输出(选择了用户从外部文件获取输入的选项)。

bob is working.
david is a new hire.
alice is bob's boss.
Segmentation fault

如果您认为需要更多代码来查找问题,请告诉我,我将添加完整程序(尽管说实话,它非常丑陋且混乱)。

有多个问题。 首先, free分配的内存。

free(input);

此外,文件需要关闭。

fclose(ip)

好的,我发现了问题所在。 我的指针 malloc 在循环之外,它从输入文件接收字符序列。 因此,它一遍又一遍地引用相同的位置......显然,当我尝试引用多行代码时,这会导致问题,因为 *input 变量仅指向代码的最后一行. 当我把它改成这样:

else if(inputExists == 1) {
        //First open the file
        inputFile = fopen(inFile, "r");
        //If said file exists
        if(inputFile) {
            while(!feof(inputFile)) {
            char *temp2 = malloc(500);
            fgets(temp2, 500, inputFile);
            if((strlen(temp2)>0) && (temp2[strlen (temp2) - 1] == '\n')) {
                temp2[strlen (temp2) - 1] = '\0';
            }
            root = insert(root, temp2);
            }
        }else {
            printf("The file/directory you specified does not exist or won't open.\n");
        }
        fclose(inputFile);
    }

代码有效。 感谢伙计们/女孩们的帮助,非常感谢,我学到了更多关于指针和fgets的知识

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM