[英]Free() doesn't work as expected after calling malloc()
我用 C 編寫了以下函數,但有兩個問題:
我被要求釋放動態分配的內存以防止使用過多的 RAM,但free(word)
只會導致我的程序出現錯誤。 如果我刪除它一切正常,為什么會發生這種情況? 我按照許多不同文章中的建議使用完word
后免費使用。
我被要求使用具有最小所需空間的 malloc,但我該怎么做? 目前我的代碼分配max_str_len
的RAM塊,但如果字要短得多像a
字母,我不希望分配200塊了點。 請問有什么建議嗎?
int read_words(char *words[], int size, int max_str_len) {
char *word;
char ch;
int i;
for (i = 0; i < size; ++i) {
word = (char *)malloc((max_str_len + 1) * sizeof(char));
if (word == NULL)
return -1;
for (int j = 0; j < max_str_len; ++j) {
scanf("%c", &ch);
if (ch == '\n') break;
if (ch == EOF || ch == 'R') return i;
word[j] = ch;
}
words[i] = word;
free(word);
}
return i;
}
您將malloc
'd char*
放入調用者提供的words[i]
,然后釋放它。 那沒有意義。 如果你釋放它,調用者就不能對它做任何事情。
如果你想要malloc
'd串是最小的,你可以realloc
他們或者你可以讀入一個大的緩沖區(在函數的開始也許分配),然后將結果復制到malloc
倒是緩沖區的大小恰到好處。
請注意,您也未能檢查scanf
是否存在錯誤,並且如果您在函數中間出現內存故障,則會導致內存泄漏——通過返回 -1,您實際上會丟失有關已填充words
元素數量的信息擁有指針。 您可能希望返回該信息( return i;
)或在malloc
失敗之前釋放該函數分配的所有指針。
您的代碼中有多個問題:
scanf()
將返回EOF
,但該字符不會被設置為EOF
,這可能不適合char
。 您應該使用getchar()
並使ch
成為int
。realloc
來縮小內存塊。這是一個修改后的版本:
int read_words(char *words[], int size, int max_str_len) {
char *word, *p;
int i, j, ch;
for (i = 0; i < size;) {
word = (char *)malloc(max_str_len + 1);
if (word == NULL) {
/* free the words allocated so far and return a failure code */
while (i-- > 0)
free(words[i];
return -1;
}
for (j = 0; j < max_str_len; ++j) {
ch = getchar();
if (ch == '\n' || ch == EOF || ch == 'R') break;
word[j] = ch;
}
if (j == 0 && (ch == EOF || ch == 'R'))
break;
word[j] = '\0';
p = (char *)realloc(word, j + 1);
if (p != NULL)
word = p;
words[i++] = word;
if (ch == EOF || ch == 'R')
break;
}
return i;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.