c语言 - 我正在执行无效指针的 free(),但无法检测到错误



我收到一个错误,提示我释放了一个无效的指针。

将大小视为 100(最大单词数(,max_str_len将大小视为 50(单词中的最大字母数,不包含"\0"。 该函数设置为扫描句子并将每个单词存储在单词数组中。

int read_words(char* words[], int size, int max_str_len){
int wordsCounter = 0;
for (int i = 0; i <size; ++i) {
words[i]=(char*)malloc(sizeof(char)*(max_str_len+1));
if(words[i]==NULL){
//in case of failure it frees every word.
for (int j = 0; j <i ; ++j) {
free(words[j]);
}
return MALLOCERROR;
}
for (int j = 0; j <max_str_len+1; ++j) {
if(scanf("%c", &words[i][j])==EOF){
wordsCounter++;
words[i][j]='';
if(j<max_str_len)
free(&words[i][j+1]);
return wordsCounter;
}
if (words[i][j]==' ') {
words[i][j] = '';
if(j<max_str_len)
free(&words[i][j+1]);
break;
}
}
wordsCounter++;
}
return wordsCounter;
}

我知道这里发生了什么;你正在分配一个很大的缓冲区,读入它,如果你不需要所有的单词空间,那么你就想把内存还给别人。这是有道理的。

你不能告诉分配器:从位置开始自由,但我们可以用realloc()做几乎同样的事情,它接受一个指针并调整数组的大小,可能将其移动到新位置。在缩短数组的情况下,它应该工作得很好。

而不是

if (j < max_str_len)
free(&words[i][j+1]); // INVALID

尝试

if (j < max_str_len)
words[i] = realloc(words[i], j+1);   // +1 for the NUL byte

这应该可以满足您的需求。

最新更新