从链表中正确删除元素?指针出现内存错误 [英] Properly removing elements from linked-list? Memory errors with pointers

查看:75
本文介绍了从链表中正确删除元素?指针出现内存错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在实现一个具有remove_entry函数和clear_table函数的哈希表.现在,我收到与remove_entry函数有关的内存读取错误.并非常感谢您的帮助

I'm implementing a hashtable that has a remove_entry function as well as a clear_table function. Right now I'm getting memory read errors pertaining to the remove_entry function. And help would be greatly appreciated

这些是我的结构:

typedef struct bucket {
   char *key;
   void *value;
   struct bucket *next;
} Bucket;

typedef struct {
   int key_count;
   int table_size;
   void (*free_value)(void *);
   Bucket **buckets;
} Table;

这是我的职能:

int remove_entry(Table * table, const char *key){
    unsigned int hc = 0;
    Bucket *curr_b;
    Bucket *next_b;

    if(table == NULL || key == NULL){
        return FAIL;
    } else {
        hc = hash_code(key)%(table->table_size);
        if(table->buckets[hc] != NULL){
            curr_b = table->buckets[hc];

            /*Check the buckets in linked list*/
            while(curr_b != NULL){
                next_b = curr_b->next;

                if(strcmp(curr_b->key,key) == 0){
                    free(curr_b->key);
                    if(table->free_value != NULL){
                        table->free_value(curr_b->value);
                    }
                    free(curr_b);
                    curr_b = NULL;
                    table->key_count--;
                    return SUCC;
                } else {
                    curr_b = next_b;
                }
            }
            return FAIL;
        }
        return FAIL;
    }
}

在删除条目并尝试读取表之后,发生了内存泄漏.我认为我删除的内容不正确.

The memory leaks come after removing an entry, and trying to read the table after. I don't think I removed things right.

内存错误:

无法弄清楚如何从终端复制/粘贴,所以他们都说

Can't figure out how to copy/paste from terminal, so they all say things like

Invalid read of size __
Address ____ is __ bytes inside a block of size ___ free'd

推荐答案

您需要考虑以下情况,其中 table-> buckets [hc] 是您释放的存储桶.

You need to consider the case where table->buckets[hc] is the bucket you free.

紧靠 free(curr_b-> key); 之前:

if(curr_b == table->buckets[hc]) {
    table->buckets[hc] = next_b;
}

现在,您释放了一个存储桶,但 table-> buckets [hc] 仍指向该存储桶.因此,下次阅读时,您正在读取释放的内存.因此就是错误.

As it is now, you free a bucket, but table->buckets[hc] still points to it. So the next time you read it you are reading free'ed memory. Thus the error.

此外,您需要跟踪上一个存储桶,以便在删除存储桶时可以将前一个存储桶指向下一个存储桶.

Also, you need to keep track of the previous bucket so you can point the previous bucket to the next bucket when you remove a bucket.

这篇关于从链表中正确删除元素?指针出现内存错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆