Home > Back-end >  Allocation of double struct pointer
Allocation of double struct pointer

Time:12-03

I have the following Hash_table and Hash_bucket structs

typedef struct Hash_Table{
   struct Bucket** bucket;
}Table;

typedef struct Bucket{
   struct Bucket* next;
   int num;
}Bucket;

I want to allocate 5 Hash Tables which i do like this,

Table** hash_tables = malloc(sizeof(Table*)* 5);
for(int i = 0; i <=4 ; i  ){
  hash_tables[i] = NULL;
} 

To my knowledge, what I have done up to here is correct, and I want to proceed allocating the Hash Tables in my code. As i did with the double pointer above, my allocation for the Hash Table

hash_table[0] = malloc(sizeof(Table));
hash_table[0]->bucket = malloc(sizeof(Bucket*)*10);  /* line 2 that is problematic*/

I allocate the size for a Hash_Table and then 10 Hash_Bucket pointers. However, I am having leaks and NOT because I free the memory wrongly. The line 2 of the allocation seems to be redundant (?) and if I replace the Hash_Table with

typedef struct Hash_Table{
   struct Bucket* bucket[10];
}Table;

, then the line 2 is not needed, everything works perfect and memory is free'd. I really am clueless as to what I am doing wrong. I've found the mistake, but don't see the mistake in the first place. Thank you all.

CodePudding user response:

The Code you posted without the "line 2 is redundant" part should look like this right:

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;
}

If you add the right free's at the bottom you shouldn't have memory leaks. At least Valgrind says so.

Note: for every written malloc in your code, you need at least 1 free

  • Related