我必须动态分配单词数组。单词存储在由空格字符的变量计数分隔的文件中。我不知道文件中有多少个单词,它们可以有不同的长度。
我有这样的代码:
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日志很长,我也要把它贴出来吗?
发布于 2012-11-26 07:38:15
其中一个问题是您在readWord中执行了realloc。如果realloc分配了一个新的缓冲区,而不是仅仅扩展当前的缓冲区,那么你的代码将会崩溃(你会双倍释放指针),这就是Valgrind所选择的。为了解决这个问题,我会重写代码,让它返回一个指针而不是void。
char * 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';
return word;
}然后将readList中的循环更改为:
while (fscanf(f, " %c", &val) == 1) {
wcount++;
arr = realloc(arr, wcount * sizeof (char *));
arr[wcount-1]=malloc(sizeof(char));
arr[wcount - 1] = readWord(f, arr[wcount-1], val);
printf("%s\n", arr[wcount-1]);
}https://stackoverflow.com/questions/13550254
复制相似问题