我必须动态分配单词数组。单词存储在由可变数量的空白字符分隔的文件中。我不知道文件中有多少个单词,它们可以有可变长度。
我有这个代码:
void readWord(FILE* stream, char *word, char first_c) {
word[0] = first_c;
char val;
int wlen = 1;
// isWhitespac is my function - tests if char is blank or '\n'
while ((val = fgetc(stream)) != EOF && isWhitespace(val) == 0) {
wlen++;
word = realloc(word, (wlen+1) * sizeof (char));
word[wlen-1] = val;
}
word[wlen] = '\0';
}
int readList(const char *file) {
FILE* f;
char **arr;
char val;
int wcount = 0;
arr = malloc(sizeof (char*));
f = fopen(file, "r");
while (fscanf(f, " %c", &val) == 1) {
wcount++;
arr = realloc(arr, wcount * sizeof (char *));
arr[wcount - 1] = malloc(sizeof (char));
readWord(f, arr[wcount-1], val);
printf("%s\n", arr[wcount-1]);
}
for (int i = 0; i < wcount; ++i) {
free(arr[i]);
}
free(arr);
fclose(f);
return 0;
}
它似乎工作正常,它读取打印所有单词。但是当我用 Valgrind 运行程序时,错误太多,我找不到。有人可以帮我吗?(我知道我必须测试 malloc 和其他人是否正常,这只是一个测试函数。)
Valgrind 日志很长,我也应该发布它吗?