且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

从链表中正确删除元素?指针出现内存错误

更新时间:2022-04-14 21:34:40

您需要考虑以下情况,其中 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.