当我尝试释放一个恶意的对象时,运行valgrind似乎意味着我让事情变得更糟。 例如,这是我的代码:
for(next_token = TKGetNextToken(tokenizer); next_token != NULL; next_token = TKGetNextToken(tokenizer))
{
ItemType* item = malloc(sizeof(ItemType));
item->data = to_lower(next_token);
item->fileName = filename;
item->occ = 1;
HM_Put(hm, item);
free(next_token);
}
现在,使用上面的代码,我被告知字节肯定在项目被malloc'd的行上丢失了。 但是,如果我在free(next_token)下添加free(item),不仅肯定会丢失该语句,而且在堆摘要之前我会收到大量无效读取。如果有人能为我提供一些帮助,我完全不知道如何解决这个问题。谢谢
我猜next_token
是一个字符串,并且to_lower
不会创建新字符串。这意味着在释放next_token
后,item->data
仍然指向释放的内存。
某种方法在关闭分词器后释放ItemType
。如果您之前释放它们,标记化将读入释放的内存,这是您非常不想做的事情。
我想你的框架应该提供某种方法来释放任何输入HM_Put
.如果没有,您需要自己执行此操作。
例如(这可以通过决定在令牌和to_lower
ed令牌之间保留哪个来优化):
typedef struct t_tofree {
struct t_tofree *next;
ItemType *item;
char *token; // Maybe superfluous if item->data points here...
};
t_tofree *toFree = NULL;
void mustFree(ItemType *item, char *token) {
t_tofree *new = malloc(sizeof(t_tofree));
new->next = toFree;
new->item = item;
new->token = token;
toFree = new;
}
void freeAll() {
while (toFree) {
t_toFree *next = toFree->next;
free(toFree->token); toFree->token = NULL;
// The line below if token is *not* data and both were allocated.
free(toFree->item->data; toFree->item->data = NULL;
// Other cleanup on item?
free(toFree->item); toFree->item = NULL;
free(toFree); toFree = next;
}
}
...
for(next_token = TKGetNextToken(tokenizer); next_token != NULL; next_token = TKGetNextToken(tokenizer))
{
ItemType* item = malloc(sizeof(ItemType));
item->data = to_lower(next_token);
item->fileName = filename;
item->occ = 1;
HM_Put(hm, item);
// Probably you can free next_token here, and only store item->data
mustFree(item, next_token);
}
...
// Here you're REALLY REALLY sure you won't use tokens or items
// (it's agreed that TKGetNextToken returns alloc'ed memory)
freeAll();