【问题标题】:Odd Seg Fault error when scanning lines from a file in C从 C 中的文件扫描行时出现奇怪的 Seg Fault 错误
【发布时间】:2013-02-07 03:22:24
【问题描述】:

我一直在开发一个程序,我需要使用 C 来扫描文件中的行并将它们存储在结构中。

我的 .txt 文件格式为:

NAME 0.2 0.3
NAME2 0.8 0.1

或者通常它是一个字符串,后跟两个双打

我的结构是:

struct device {
char* name;
double interruptProbability, interruptTime, startTime, endTime;
} myDevice;

现在,我可以很好地扫描这些行,但是当需要将它们放入我的结构时,有些事情会变得一团糟。以下是我进行扫描的方式:

    char line[BUFSIZ];
    while(fgets (line, BUFSIZ, devicesFile) != NULL){
        struct device *d = &myDevice;
        if(!isspace(*line)){
            printf("String: %s \n", &line);
            d->name = "success"; // for testing purposes
            printf("device name before: %s \n", d[0]);
            sscanf(line, "%s %f %f",&d->name, &d->interruptProbability, &d->interruptTime);
            printf("device name after: %s \n", d[0]);
        }
    }

当我运行它时,它会打印出来:

String: Disk 0.2 0.00005


device name before: success 

在给我一个段错误之前。

我运行 GDB 来测试扫描的结果,无论出于何种原因,它都会将其放入 d->命名一个巨大的十六进制数字,该数字旁边有(地址越界)。

有什么想法吗?

【问题讨论】:

    标签: c file segmentation-fault


    【解决方案1】:

    这是因为您在 sscanf 调用中覆盖了文字字符串。 d->name 指向一个文字字符串,它们是只读的并且具有固定长度(因此,如果您尝试获取的字符串长度超过 7 个字符,您也可以尝试将其写到末尾)。

    您需要为d->name 使用数组或在堆上为其分配内存。

    【讨论】:

      【解决方案2】:

      您没有为每个char *name 分配空间。您需要在调用 sscanf 之前添加 d->name = (char *)malloc(<length of the token>*sizeof(char)+1)

      【讨论】:

        【解决方案3】:

        您不能将字符串扫描到指针d->name

        即使你给它分配了一个常量值也不行:

        d->name = "success"; // for testing purposes
        

        你需要为它分配内存,或者把它变成一个数组。你应该非常小心使用sscanf 来读取字符串。最好使用strtok 或仅使用strchr 查找第一个空格,然后使用strdup 复制字节。

        char *next = strchr(line, ' ');
        if( next != NULL ) {
            *next++ = 0;             // Terminate string and move to next token.
            d->name = strdup(line);  // Make a copy of tokenised string
        
            // Read the floats - note you should check that the result is equal to 2.
            count = sscanf(next, "%f %f", d->interruptProbability, d->interruptTime);
        }
        

        【讨论】:

          【解决方案4】:

          您正在扫描字符串文字。字符串文字在 C 和 C++ 中是 const char*s,是只读的,因此 sscanf 在尝试写入字符串文字“success”时会崩溃。

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2020-10-19
            • 1970-01-01
            • 1970-01-01
            • 2020-02-05
            • 1970-01-01
            • 2012-07-26
            相关资源
            最近更新 更多