Search code examples
cstringfopenfgets

fgets in function gets segmentation fault with a variable, but not with hard coded string


I'm trying to loop through a .desktop file and get some values out of it, line-by-line, and storing it all inside of a structure. I want to do this with many files, so it's important to be able to store a file path as a variable and send that to the function.

Here is the function that is getting the error:

App * ParseApp (char * path) {
    printf("Path: %s\n", path);

    FILE * file = fopen(path, "r");
    char line[256];

    App * app = malloc(sizeof(struct App));

    printf("Malloc worked. sizeof line: %li\n", sizeof(line));

    while (fgets(line, sizeof(line), file)) {
        printf("about to parse line\n");
        ParseLine(app, line);
    }

    return app;
}

The following code does work, and outputs the value expected:

App * app = ParseApp("/usr/share/applications/Android Studio.desktop");
printf("Name: %s", app->name);

However, when using a variable to pass the filepath as an argument, I get a segfault:

char filepath[128];
strcpy(filepath, settings.folder);
strcat(filepath, "/");
strcat(filepath, filename);
App * app = ParseApp(filepath);

I am confident that fgets is where I am getting a segfault, because it properly outputs the file path at the start of the function, and it even gets past the malloc function:

Path: /usr/share/applications/Android Studio.desktop

Malloc worked. sizeof line: 256
Segmentation fault (core dumped)

So it seems that only hard coded string values will work. I figured the issue might be a size issue with the string variable, but seeing as how it outputs the same way in either case, that doesn't seem to be the issue.

I added a check to see if the file is null:

App * ParseApp (char * path) {
    printf("Path: %s\n", path);

    FILE * file = fopen(path, "r");
    char line[256];

    if (file == NULL)
        printf("file is null\n");

    App * app = malloc(sizeof(struct App));

    printf("Malloc worked. sizeof line: %li\n", sizeof(line));

    while (fgets(line, sizeof(line), file)) {
        printf("about to parse line\n");
        ParseLine(app, line);
    }

    return app;
}

And it does output file is null, so I guess the problem lies in fopen.


Solution

  • Newline character messed up fopen, adding filepath[strcspn(filepath, "\n")]=0; solved it. Thank you for the help, especially user3121023.