[英]Allocation of double struct pointer
我有以下 Hash_table 和 Hash_bucket 結構
typedef struct Hash_Table{
struct Bucket** bucket;
}Table;
typedef struct Bucket{
struct Bucket* next;
int num;
}Bucket;
我想分配 5 個 Hash 表,我喜歡這樣做,
Table** hash_tables = malloc(sizeof(Table*)* 5);
for(int i = 0; i <=4 ; i++){
hash_tables[i] = NULL;
}
據我所知,我在這里所做的是正確的,我想繼續在我的代碼中分配 Hash 表。 正如我對上面的雙指針所做的那樣,我對 Hash 表的分配
hash_table[0] = malloc(sizeof(Table));
hash_table[0]->bucket = malloc(sizeof(Bucket*)*10); /* line 2 that is problematic*/
我為 Hash_Table 分配大小,然后分配 10 個 Hash_Bucket 指針。 但是,我有泄漏,而不是因為我錯誤地釋放了 memory。 分配的第 2 行似乎是多余的(?),如果我將 Hash_Table 替換為
typedef struct Hash_Table{
struct Bucket* bucket[10];
}Table;
,則不需要第 2 行,一切正常,並且 memory 是免費的。 我真的對我做錯了什么一無所知。 我發現了錯誤,但一開始就沒有看到錯誤。 謝謝你們。
您發布的沒有“第 2 行是多余的”部分的代碼應該如下所示:
typedef struct Bucket {
struct Bucket* next;
int num;
} Bucket;
typedef struct Hash_Table {
struct Bucket** bucket;
} Table;
int main(void)
{
// Create hashtable
Table** hash_tables = malloc(sizeof(Table*) * 5);
for (int i = 0; i <= 4; i++) {
hash_tables[i] = NULL;
}
// Create Bucket
hash_tables[0] = malloc(sizeof(Table));
hash_tables[0]->bucket = malloc(sizeof(Bucket*)*10); /* line 2 that is problematic*/
free(hash_tables[0]->bucket);
free(hash_tables[0]);
free(hash_tables);
return 0;
}
如果你在底部添加正確的免費的,你不應該有 memory 泄漏。 至少Valgrind是這么說的。
注意:對於您的代碼中的每一個malloc
,您至少需要 1 個free
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.