【问题标题】:Why am I getting segmentation Fault on fscanf() function?为什么我在 fscanf() 函数上出现分段错误?
【发布时间】:2020-05-20 11:14:19
【问题描述】:

我不明白为什么在调用 fscanf() 函数时会出现分段错误。我知道我使用 fopen() 正确打开了文件。

ST_CHAR* GetLeafFromBitmap(const ST_CHAR* filename, ST_UINT8 u8dido, ST_UINT16 u16idx)
{
    FILE* fp;
    ST_CHAR* ps8buff;
    ST_CHAR ps8numstring[20];
    ST_CHAR* ps8curleaf;
    ST_CHAR  ps8didostr[10];
    ST_CHAR  ps8idxstr[10];

    sprintf(ps8idxstr, "%d", u16idx);   
    sprintf(ps8didostr, "%d", u8dido);
    strcpy(ps8numstring, ",");
    strcat(ps8numstring,ps8idxstr);
    strcat(ps8didostr, ps8numstring);
    printf("didostr : %s\n", ps8didostr);
    if((fp = fopen(filename, "r")) == NULL)
    {
        fprintf(stderr, "\nError %d: Loading from \"%s\" file failed: %s\n", errno, filename, strerror(errno));
        return -1;
    }       
    while(fscanf(fp, "%s", ps8buff) != EOF)
    {
        if(strstr(ps8buff, ps8didostr) != NULL)
        {
            ps8curleaf = GetLeaf(ps8buff);
            return ps8curleaf;
        }
    }
    return NULL;
}

如果任何代码专家能指出我可能做错了什么以得到错误,我将不胜感激。

【问题讨论】:

  • ps8buff 是一个指针,但是它指向哪里?

标签: c segmentation-fault


【解决方案1】:
ST_CHAR* ps8buff;
...
while(fscanf(fp, "%s", ps8buff) != EOF)

两件事:

1) 您正在写入一个未初始化的指针,您需要为其保留空间(通过malloc)或使用类似ST_CHAR ps8buff[some_size];的数组

2) 您不必在fscanf 中检查EOF,如果成功,它会返回成功匹配和分配的输入项的数量,而不是:

while(fscanf(fp, "%s", ps8buff) == 1)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-01-07
    • 1970-01-01
    • 1970-01-01
    • 2019-03-15
    • 1970-01-01
    • 2020-03-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多