我是一个新的c,为了解它,我试图写一个函数来手动读取std输入的字符。该程序将从std读取行并输出它们,ant会在遇到空行时结束。双免费或腐败错误发生时,免费呼叫c
但是,如果输入流只包含三行或更少的行,它会工作正常,但如果输入包含4行以上,它总是会停止并显示错误。调用realloc和释放函数时发生错误:'double free或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;
}
的执行结果是:
[email protected]:~/vmshared$ ./mylib2
abc
def
hij
The lines you typed are:
- abc.
- def.
- hij.
[email protected]:~/vmshared$ ./mylib2
11
22
33
44
*** Error in `./mylib2': double free or corruption (fasttop): 0x00000000017f1030 ***
你为什么用C++标记它? –
你的代码和问题类似于http://stackoverflow.com/questions/24592631/realloc-invalid-next-size-and-malloc-memory-corruption-fast/24592774 – deviantfan
这个问题已经解决了这个问题:[ C - 如果使用realloc是免费的必需?](http://stackoverflow.com/questions/5426700/c-if-realloc-is-used-is-free-necessary) –