使用fscanf()进行分段错误

时间:2017-06-13 17:57:15

标签: segmentation-fault scanf

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

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错误。

1 个答案:

答案 0 :(得分:1)

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