首页 > 解决方案 > 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

但是,当我将它复制到视觉工作室时,它可以正常工作

功能

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;
}

标签: csegmentation-faultfeof

解决方案


推荐阅读