我是一個新的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) –