简体   繁体   English

函数中的 fgets 使用变量获取分段错误,但使用硬编码字符串则没有

[英]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.我正在尝试遍历.desktop文件并从中逐行获取一些值,并将其全部存储在结构中。 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:我确信 fgets 是我遇到段错误的地方,因为它在函数开始时正确输出文件路径,它甚至通过了 malloc 函数:

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.它确实输出file is null ,所以我猜问题出在 fopen 上。

Newline character messed up fopen, adding filepath[strcspn(filepath, "\n")]=0;换行符弄乱了 fopen,添加了filepath[strcspn(filepath, "\n")]=0; solved it.解决了它。 Thank you for the help, especially user3121023.感谢您的帮助,尤其是 user3121023。

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

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