简体   繁体   中英

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

Here is a snippet of code from my program that is causing an segmentation error on the last line. My program is supposed to take input from a file (if that is specified by the user) or from manual input from the console. When the user inputs the sentences by the console, it works. However, when I take the sentences from an external file, I get a segmentation fault on the last line (the line where when it is completed EOF will be reached). Assume the file is closed and the memory freed outside of this snippet .

Here is the snippet:

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

Here is what is on the external file:

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

This is the output that I get when the full program (where the option for the user taking input from an external file is selected).

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

If you think you need more code to find the problem let me know and I will add the full program (though to be honest it is very ugly, and messy).

There are multiple problems. To start with, free allocated memory.

free(input);

Also, file needs to be closed.

fclose(ip)

Ok guys I found out what the problem was. I had my pointer malloc'd outside of the loop where it receives the character sequences from the input file. Because of this it was referencing the same location over, and over again....apparently this was causing issues when I tried to reference more than one line of code, as the *input variable was only pointing to the last line of the code. When I changed it to this:

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);
    }

the code worked. Thanks for the help though guys/gals, it was greatly appreciated and I learned alot more about pointers and fgets in general

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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