gpt4 book ai didi

c - 自由(): invalid next size (fast) in C

转载 作者:行者123 更新时间:2023-11-30 15:59:21 25 4
gpt4 key购买 nike

过去几天我一直在尝试找出程序中的这个错误。如果我增加 #defined LINE_SIZE 的大小,它在我的测试用例上工作得很好。 ,但这只是暂时解决我的问题。

在这部分代码中,我读取文件中的每一行,并为我找到的每个特定字符在内存中增加一个位置。 ascii 指向 malloc 'd 面积为 256 个整数。

void readFile(FILE *fp, int *ascii) {
char *line;
char *temp;

while (!feof(fp)) {
line = readLine(fp);
if (line == NULL)
break;
temp = line;
while (*temp != '\0') {
(*(ascii + *temp))++;
temp++;
}
free(line); <-------------- BREAKS HERE
}
fclose(fp);
}

char* readLine(FILE *fp) {
char *rtn = NULL;
int last = -1;
int size = LINE_SIZE; <------ LINE_SIZE = 8

do {
rtn = (char*)realloc(rtn,size);
if (!rtn) {
printf("Realloc failed\n");
exit(1);
}
fgets(rtn + last + 1, size, fp);
if (feof(fp))
break;
last = strlen(rtn) - 1;
size += size;
if (rtn[last] == '\n')
break;
} while (rtn[last] != '\0');
return rtn;
}

我试图让我的代码读取自己的 .c 文件,但它在 250 行文件中的第 58 行处中断:void makeList(int *ascii, LinkNode *list) {

在gdb中,打印line就在我自由之前,它给了我:

(gdb) print line
$1 = 0x9849578 "void makeList(int *ascii, LinkNode *list) {\n"

这正是我期望它打印的内容。当代码尝试释放我不再需要的这一行时,代码立即崩溃。

最佳答案

您没有将正确的缓冲区大小传递给fgets()。即使您分配了那么多字节,您还是将偏移量传递到缓冲区中,并且需要考虑到这一点:

fgets(rtn + last + 1, size - last - 1, fp);

关于c - 自由(): invalid next size (fast) in C,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9048421/

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