gpt4 book ai didi

C - fgets 返回损坏的数据

转载 作者:行者123 更新时间:2023-11-30 16:46:31 25 4
gpt4 key购买 nike

我正在制作一个程序,该程序应该读取一个文件并根据它做一些事情,但是我似乎在正确读取该行时遇到问题。我正在使用 while 循环来执行此函数:

static int readLineFromFile(char **destination, int *allocSize, FILE *file)
{
char *newDest;
if (fgets(*destination, (*allocSize) - 2, file))
{
int strend = strlen(*destination);
while (*(*destination + strend - 1) != '\n')
{
printf("\"%s\"\n", *destination);
size_t length = (*allocSize) * 2; //WE ARE GOING TO ALLOCATE MORE MEMORY AND KEEP READING
newDest = realloc(*destination, length);
if (!newDest)
{
free(*destination);
return 2; //2 - FAILED ALLOC
}
*destination = newDest;
fgets(*destination + strend, (length / 2), file);
*allocSize = length;
strend = strlen(*destination);
}
*(*destination+strend-1) = '\0'; //WE DONT NEED THE \n AT THE END, SO WE JUST REPLACE IT WITH \0
printf("D %s\n", *destination);
return 0;
}
else{
if (feof(file)) { //IF NOTHING IS LEFT TO READ, WE CHECK IF IT IS BECAUSE OF EOF (1) OR AN ERROR (2)
return 1;
}
return 2;
}
}

其中 **destination 是指向字符串分配区域的指针,*allocSize 是 **destination 大小的指针,*file 是文件流的指针。

但是,在第二次重新分配之后(因此,在我有比 allocSize 长的 2 行并且必须重新分配之后,到底有多少行之后并不重要), printf-s (在 realloc while 循环之后和在realloc 周期的开始)正确返回 5 个字符,然后返回 4 个随机字符(“ABCDE???”而不是“ABCDEFGHIJK...”)。我认为这是因为 while 循环中稍后的 strtok 函数(在阅读该行之后),但似乎并非如此。

然后我发现,在代码的后面,我为加载的行的解析子字符串分配了空间 - 如果我删除这部分代码,一切都会再次正常工作(甚至不重要,我分配了多少字节,我仍然不断收到损坏的字符串)。所以在这一点上我什至开始思考我是否没有以某种方式破坏操作系统。

所以,如果有人能告诉我这个函数是否有错误,或者我是否应该在其他地方寻找它,那就太好了。谢谢。

此外,以下是 while 循环中的其他代码:STRTOK,fileLine 是 *readLine 的目的地:

char *strtokStart = malloc (strlen (fileLine)+2);
strcpy (strtokStart, fileLine);
char *strtokSave = fileLine;
strcpy (newKey, strtok_r (fileLine, "=", &strtokSave));
strcpy (newValue, strtok_r (NULL, "\n", &strtokSave));
free (strtokStart);

分配附加字符串:

config->topKey->key = (const char *) malloc(strlen(newKey) + 1);
config->topKey->value = (const char *) malloc(strlen(newValue) + 1);
if (!(config->topKey->key && config->topKey->value))
{
printf("ALLOC FAIL\n");
statusVal = 1;
break;
}

最佳答案

readLineFromFile 有两个问题:

  1. 如果文件不是以\n 结尾,则 while 循环将继续分配更多内存,直到 realloc 失败。检查第二个 fget 的返回码确实检测到这种情况!
  2. 失败的重新分配的错误处理:free(*destination) 给调用者留下了错误的指针。最好直接删除免费的。或者添加 *destination=NULL。

否则 readLineFromFile 就可以,并且应该适用于有效的输入文件。如果没有无效的输入文件,代码中的其他地方可能存在更多错误。

当然,应该使用 malloc 缓冲区调用 readLineFromFile。

关于C - fgets 返回损坏的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43699620/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com