Memory allocation problem in HashTable

后端 未结 4 399
清歌不尽
清歌不尽 2021-01-24 17:18

Please don\'t close this saying a duplicate question. I made an important change so not to confuse people, I resubmitted this much clearer codes.

4条回答
  •  逝去的感伤
    2021-01-24 17:47

    Personally I am not a huge fan of using typedefs, especially when you are a beginner. I think that may be partially what is confusing you. You are better avoiding things like:

    typedef struct hashtable * HashTablePtr;
    

    Using to many typedefs will make your code harder to read since you will need to constantly look up what they are referring too.

    The main problem is that you were allocating the memory for the size of a hashtable/list pointer and not for the size of their respected structures. I think the code below shows this well. You will also want to check if you allocations worked. If malloc, calloc, realloc. etc. fail they return NULL. If this happens and you do not check for this case you will get a segfault error and your program will crash.

    Also follow the c99 standard, and put all of your variable declarations at the start of the function.

    c99 std

    malloc manpage

    struct hashtable *
    createHashTable(unsigned int capacity){
        struct hashtable *hash;
        struct list *mylist;
    
        /* You want to allocate size of the hash structure not the size of a pointer. */
        hash = malloc(sizeof(struct hashtable)); 
        // always make sure if the allocation worked.
        if(hash == NULL){
            fprintf(stderr, "Could not allocate hashtable\n");
            return NULL;
        }
    
        hash->size = 0;
        hash->capacity = capacity;
    
        /* Unless you need the memory to be zero'd I would just use malloc here
         * mylist = calloc(capacity, sizeof(struct list)); */
        mylist = malloc(capacity * sizeof(struct list));
        if(mylist == NULL){
            fprintf(stderr, "Could not allocate list\n");
            free(hash); /* free our memory and handle the error*/
            return NULL;
        }
    
        mylist->head = NULL;
        mylist->size = 0;
        mylist->tail = NULL;    
        hash->list = mylist;
    
        return hash;
    }
    

    Also remember to free you list before you free your hashtable:

    free(myhash->list);
    free(myhash);
    

提交回复
热议问题