Search code examples
cmemorystructhashtableallocation

Proper Memory allocation


I have the following construction:

typedef struct bucket {
    char *key;
    ENTRY *data;
    struct bucket *next;
} bucket;

typedef struct {
    size_t size;
    bucket **table;
} hash_table;

But I have no idea how to allocate memory for that. I tried:

hash_table* ht = malloc(sizeof(hash_table)*101);

in order to create a hashtable for 101 entries but it din't work! Can anyone help me? I would really appreciate it!


Solution

  • Not quite. Assuming this is C, you probably want to make a function:

     hash_table* init_table(size_t size) {
         size_t i;
         hash_table* ht = (hash_table*)malloc(sizeof(hash_table));
         if (ht == NULL) return NULL;
         ht->size = size;
         ht->table = (bucket**)malloc(sizeof(bucket*)*size);
         if (ht->table == NULL) {
             free(ht);
             return NULL;
         }
         for (i = 0; i < size; ++i) {
             ht->table[i] = NULL;
         }
         return ht;
     }
    

    You might need some other fields in that struct.

    If you wanted to be tricky, and never realloc the bucket, you can do this:

     hash_table* init_table(size_t size) {
         hash_table* ht = (hash_table*)malloc(sizeof(hash_table)+sizeof(bucket)*size);
         if (ht == NULL) return NULL;
         ht->size = size;
         ht->table = (bucket**)(ht+1);
         for (i = 0; i < size; ++i) {
             ht->table[i] = NULL;
         }
         return ht;
     }
    

    EDIT: I fixed my bucket* table's to bucket**

    EDIT2: I've gotten rid of the memsets and added error checking for malloc.