【问题标题】:Segmentation Fault using fscanf()使用 fscanf() 的分段错误
【发布时间】:2017-06-13 17:57:14
【问题描述】:

我正在尝试读取一个非常简单的数据文件,如下所示:

1597 1 0 3 1 

使用以下代码:

void boot(){
FILE *f = fopen("shutdown.txt", "r");
    uint8_t timestamp = 0;
    uint8_t power_down_type = 0;
    uint8_t power_down_cause = 0;
    uint8_t boot_number = 0;
    uint8_t antenna_deployed = 0;
    uint8_t images_captured = 0;

    fscanf(f, "%u %d %d %d %d %d", &timestamp, &power_down_type, &power_down_cause, &boot_number, &antenna_deployed, &images_captured);

    printf("timestamp: %u\n", timestamp);
    printf("power_down_type: %d\n", power_down_type);
    printf("power_down_cause: %d\n", power_down_cause);
    printf("boot_number: %d\n", boot_number);
    printf("antenna_deployed: %d\n", antenna_deployed);
    printf("images_captured: %d\n", images_captured);
}

但是当我运行代码时,我得到了一个 SEGV 错误。

【问题讨论】:

  • "%u" 期待unsigneduint8_t 不是 unsigned。使用"%hhu"。详情请查看fscanf() 文档。

标签: segmentation-fault scanf


【解决方案1】:

%d 读取 int%u 读取 unsigned int,两者都大于 uint8_t。通过写入超过变量的大小会发生未定义的行为。 %hhu 应该用于uint8_t

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-03-29
    • 2015-02-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-25
    • 1970-01-01
    相关资源
    最近更新 更多