feof 导致分段错误核心转储错误?

问题描述

我正在尝试创建一个文件获取动态分配的字符串的函数,忽略前导空格并继续直到它再次到达空格,但我一直收到“分段错误(核心转储)”错误。我尝试使用 valgrind 来查找原因,它说明了 feof

Invalid read of size 4
==1155740==    at 0x48EDE24: feof (feof.c:35)
==1155740==    by 0x1095E7: my_string_extraction (my_string.c:73)
==1155740==    by 0x109285: main (main.c:10)
==1155740==  Address 0x0 is not stack'd,malloc'd or (recently) free'd

但是,当我将其复制到 Visual Studio 时,它可以正常工作

功能

Status my_string_extraction(MY_STRING hMy_string,FILE* fp)
{
        char currCh;
        int i = 0;
        int x = 0;
        int wordStart = 0;
        struct My_string* temp = hMy_string;
        char* tempData;
        while (!feof(fp))
        {
                currCh = fgetc(fp);
                if ((currCh == ' ' || currCh == '\n' || currCh == '\t' || feof(fp)) && wordStart != 0)
                {
                        temp->data[i] = '\0';
                        temp->size = i - 1;
                        fseek(fp,-1,SEEK_CUR);
                        return SUCCESS;
                } else if (currCh == ' ' || currCh == '\n' || currCh == '\t') {
                } else {
                        if ((i+1) >= temp->cap)
                        {
                                tempData = (char*) malloc(sizeof(char) * temp->cap * 2);
                                for(x = 0; x < temp->size; x++)
                                {
                                        tempData[x] = temp->data[x];
                                }
                                free(temp->data);
                                temp->data = tempData;
                                temp->cap = temp->cap * 2;
                        }
                        wordStart = 1;
                        temp->data[i] = currCh;
                        i++;
                        temp->size = i;
                }
        }
        temp->data[i + 1] = '\0';
        return FAILURE;
}

主要

#include <stdio.h>
#include <stdlib.h>
#include "my_string.h"
int main(int argc,char* argv[])
{
        MY_STRING hMy_string = NULL;
        FILE* fp;
        hMy_string = my_string_init_default();
        fp = fopen("Spring2019/COMP1020/HANGMAN/simple.txt","r");
        my_string_extraction(hMy_string,fp);

        my_string_destroy(&hMy_string);
        //fclose(fp);
        return 0;
}

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)