int parseString(char* input, char*** words, int* size) {
char *word;
*words = malloc(sizeof(char));
word = strtok(input, " \n\t");
while (word != NULL) {
(*words)[*size] = malloc(sizeof(word) + 1);
strcpy((*words)[*size], word);
(*size)++;
*words = realloc(*words, ((*size) + 1) * sizeof(char));
word = strtok(NULL, " \n\t");
}
return 0;
}
我想收到一個字符串(input
)並將其拆分爲單詞並存儲單詞。C realloc()char **「無效的下一個大小」錯誤
在第四迭代(總是在第四,從來沒有更早)在while循環我在realloc(...)
得到一個錯誤:
realloc(): invalid next size: 0x0000000001641010 ***
Aborted (core dumped)
製作後,建議改由@TaylorBrandstetter製成,@chux代碼看起來像這樣:
int parseString(char* input, char*** words, int* size) {
char *word;
*words = malloc(sizeof(char*));
word = strtok(input, " \n\t");
while (word != NULL) {
(*words)[*size] = malloc(strlen(word) + 1);
strcpy((*words)[*size], word);
(*size)++;
*words = realloc(*words, ((*size) + 1) * sizeof(char*));
word = strtok(NULL, " \n\t");
}
return 0;
}
對於初學者來說,爲'* words'分配單個字節對於*指針*的數組來說沒有足夠的空間(每個可能有4或8個字節)。並且'sizeof(word)'不會告訴你字符串的大小,只有'char *'的大小。請記住,'sizeof'計算不會在運行時發生。 – 2014-10-30 18:15:36
您可能希望啓用編譯器的警告(命令行選項'-Wall -Wextra -pedantic' for gcc),然後修復您的代碼,直到不再發出警告。 – alk 2014-10-30 18:17:46
建議'strlen(單詞)'而不是'sizeof(單詞)'。 – chux 2014-10-30 18:26:16