从结构中释放双指针

时间:2017-03-30 18:03:45

标签: c memory-management struct free calloc

我的delete_table函数有问题。所以我有两个结构

struct _entry_ {
    int key;
    int data;
    struct _entry_* next;
    struct _entry_* prev;
};
typedef struct _entry_ entry;

struct _table_ {
    entry** entries;
    int size;
};
typedef struct _table_ table;

我使用calloc初始化我的表。

void table_init(table* ht, int initial_size) {
    ht->entries = (entry**)calloc(initial_size, sizeof(entry*));
    if (ht->entries) {
        ht->size = initial_size;
    }
}

现在我写的自由函数

void table_destroy(htable* ht) {

    entry *el, *temp;
    int i;
    for(i = 0; i < ht->size; i++) {
      el = ht->entries[i];
      while(el != NULL){
        temp = el;
        el = el->next;
        free(temp);
      }
      free(ht->entries[i]);
    }
    free(ht); // <- don't know do i need this.
}

当我用valgrind测试它时出现了这个错误

==13560== Invalid free() / delete / delete[] / realloc()
==13560==    at 0x4C2BDEC: free (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==13560==    by 0x400783: htable_destroy (htable.c:46)
==13560==    by 0x400A24: main (main.c:25)
==13560==  Address 0xffefffae0 is on thread 1's stack
==13560==  in frame #2, created by main (main.c:7)

任何帮助都会很棒,谢谢你的时间!

1 个答案:

答案 0 :(得分:1)

[shoeOrderDict setObject: @[shoeOrder objectAtIndex: 0] forKey: @"customer"];
[shoeOrderDict setObject: @[shoeOrder objectAtIndex: 1] forKey: @"size"];
[shoeOrderDict setObject: @[shoeOrder objectAtIndex: 2] forKey: @"style"];
[shoeOrderDict setObject: @[shoeOrder objectAtIndex: 3] forKey: @"color"];