【发布时间】:2014-08-26 22:17:16
【问题描述】:
我是 c 的新手,为了学习它,我正在尝试编写一个函数来手动从标准输入中读取字符。程序会从std中读取行并输出,遇到空行就结束。
但是如果输入流只包含 3 行或更少的行,它工作得很好,但如果输入包含 4 行以上,它总是会因错误而停止。调用 realloc 和 free 函数时出现错误:'double free or corruption (fasttop): 0x0000000001f46030 *',为什么?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char *readline(int *length) {
char ch, *s = NULL, *temp = NULL;
int UNIT = 3, size = 0, index = 0;
while ((ch = getchar()) != EOF) {
if (size == 0 || index >= size) {
size += UNIT;
temp = realloc(s, sizeof(char) * size);
if (s != NULL && temp != s) free(s);
s = temp;
temp = NULL;
}
s[index++] = (ch == '\n') ? '\0' : ch;
if (ch == '\n') break;
}
*length = index - 1;
return s;
}
char **readlines(int *count) {
char **lines = NULL, **tempLines = NULL;
int UNIT = 1, size = 0, index = 0;
int length = 0;
char *line = NULL;
while ((line = readline(&length)) != NULL) {
if (strlen(line) == 0) break;
if (size == 0 || index >= size) {
size += UNIT;
tempLines = realloc(lines, size * sizeof(char *));
if (lines != NULL && tempLines != lines) free(lines);
lines = tempLines;
tempLines = NULL;
}
lines[index++] = line;
}
*count = index;
return lines;
}
int main(int argc, char *argv[]) {
int length = 0, index = 0;
char **lines = readlines(&length);
printf("The lines you typed are: \n");
for (; index < length; index++) {
printf("%5s %s.\n", "-", lines[index]);
}
return 0;
}
执行结果为:
xxx@xxx:~/vmshared$ ./mylib2
abc
def
hij
The lines you typed are:
- abc.
- def.
- hij.
xxx@xxx:~/vmshared$ ./mylib2
11
22
33
44
*** Error in `./mylib2': double free or corruption (fasttop): 0x00000000017f1030 ***
【问题讨论】:
-
你为什么把它标记为 C++?
-
你的代码和问题类似于stackoverflow.com/questions/24592631/…
-
这个问题已经解决了这个问题:C - If realloc is used is free necessary?
-
关于这一行:if (s != NULL && temp != s) free(s);,函数 realloc 在复制 old are 的内容后释放 old area,除非返回的指针与原始指针相同(通常但并非总是更改。)因此,当新区域与旧区域不同时,您在 realloc 函数已释放的区域上调用 free(s)。