微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

如何解决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 举报,一经查实,本站将立刻删除。