c - 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;
}
解决方案
推荐阅读
- jquery - 自定义事件在 Jquery 中触发,但找不到任何事件处理程序
- java - 不使用 JLayeredPane 将 jcomponent 移到后面
- python - from_point 函数不会在 windows CMD 上返回预期的控件
- eclipse - 为 Eclipse 安装 groovy 插件时出现问题
- spring-boot - SpringBoot 控制器如何知道返回胡子模板而不是字符串
- visual-studio - 我无法让 log4net 过滤工作 - 似乎忽略了级别和过滤器设置
- android - 'it' 会在内部自动进行智能转换吗?
- python - 如何使用 python win32 循环遍历 excel 数据透视切片器?
- c# - 关于保存相关实体的 EF 与 EF Core
- python-3.x - 有没有办法在不丢失用户先前输入点的情况下动态绘制从用户那里获取的点?(Python)