实现哈希表/ hashmap并获取seg。尝试插入,搜索或删除时的错误(基本上所有内容)

时间:2016-09-20 02:34:21

标签: c++ hashmap segmentation-fault

由于seg,我无法在我的程序中真正做任何功能。故障。它是插入,删除,搜索的分段。如果有人可以请看看。我认为它可能是普遍存在的东西,例如可能导致它的表格查找。代码如下:

    /*
     * This program implements a hash table using linked lists
     *
     */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <iostream>
using namespace std;


/*
 * Node struct, contains key, value, and reference to next node
 */

typedef struct _node
{
    char *key;
    int value;          /* For this, value will be of type int */
    struct _node *next; /* pointer to the next node in the list */
} node;


/* HashMap class */
class HashMap
{
private:
    node ** hashTable;
    int numSlots;
public:
    /* Initializes a hashmap given its set size */
    HashMap(int size)
    {
        numSlots = size;
        hashTable = (node **) malloc (size * sizeof(node));
        if (hashTable == NULL)
        {
            fprintf(stderr, "Fatal error: out of memory. "
                    "Terminating program.\n");
            exit(1);
        }
        for (int i = 0; i < size; i++)
        {
            hashTable[i] = NULL;
        }
    }

    /* Deconstructor */
    ~HashMap()
    {
        for (int i = 0; i < numSlots; i++)
        {
            node *temp = hashTable[i];
            free_list(temp);
        }
        delete [] hashTable;
    }

    /*** Hash function. ***/

    int hash(char *s)
    {
        int i;
        int sum = 0;

        for (i = 0; * (s + i) != '\0'; i++)
        {
            sum += *(s + i);
        }

        return (sum % numSlots);
    }

    /*
     *Free all the nodes of a linked list. Helper method for *deconstructor
     */
    void free_list(node *list)
    {
        node *temp = NULL;
        char *tempKey;
        int tempValue;
        while (list != NULL)
        {
            temp = list;
            tempKey = temp->key;
            tempValue = temp->value;
            list = list->next;
            if (tempKey != NULL)
            {
                free(tempKey);
            }
            free(temp);
        }
    }

    /* Create a single node. */
    node *create_node(char *key, int value)
    {
        node *result = (node *)malloc(sizeof(node));

        if (result == NULL)
        {
            fprintf(stderr, "Fatal error: out of memory. "
                    "Terminating program.\n");
            exit(1);
        }

        result->key = key;
        result->value = value;
        result->next = NULL;

        return result;
    }


    /*
     *Stores given key/value pair in hashmap
     *returns boolean for success/failure
     */

    void set (char* key, int value)
    {
        int keyValue = hash(key);
        node *current = hashTable[keyValue];
        node *original = current;
        node *newNode = NULL;
        if (current == NULL)
        {
            hashTable[keyValue] = create_node(key, value);
        }
        else
        {
            while (current != NULL)
            {
                current = current -> next;
            }

            if (current == NULL)
            {
                newNode = create_node(key, value);
                newNode -> next = original;
                hashTable[keyValue] = original;
            }
        }
    }

    /* Return a float value representing the load factor 
     *(item in hash map)/(size of hash map) of the data structure.
    */

    float load()
    {
        float numUsed = 0.0;
        for (int i = 0; i < numSlots; i++)
        {
            if (hashTable[i] != NULL)
            {
                numUsed++;
            }
        }
        return (numUsed / numSlots);
    }

    /* Removes value corresponding to inputted key from table */

    int remove (char* key)
    {
        int keyValue = hash(key);
        node *listOfInterest = hashTable[keyValue];
        if (listOfInterest == NULL)
        {
            return -999;
        }
        int toReturn = listOfInterest -> value;
        free(listOfInterest);
        return toReturn;
    }

    /*
     * Look for a key in the hash table.  Return -999 if not found.
     * If it is found return the associated value.
     */
    int get(char *key)
    {
        int keyValue = hash(key);

        node *listOfInterest = hashTable[keyValue];

        while (listOfInterest != NULL)
        {
            if (listOfInterest != NULL)
            {
                return listOfInterest->value;
            }
            listOfInterest = listOfInterest -> next;
        }

        return -999;
    }

    /* Prints hash table */

    void print_hash_table()
    {
        int i;
        node *listIterator = NULL;

        for (i = 0 ; i < numSlots ; i++)
        {
            listIterator = hashTable[i];
            while (listIterator != NULL)
            {
                printf("%s %d\n", listIterator->key, listIterator -> value);
                listIterator = listIterator -> next;
            }
        }

    }
};


int main()
{
    HashMap hash (128);
    char* key;
    int value;
    int choice;
    int deleted;
    while (1)

    {
        cout << "\n----------------------" << endl;
        cout << "Hash Table Options" << endl;
        cout << "\n----------------------" << endl;
        cout << "1.Insert element into the table" << endl;
        cout << "2.Search element given key" << endl;
        cout << "3.Delete element given key" << endl;
        cout << "4.Calculate load" << endl;
        cout << "5.Exit" << endl;
        cout << endl;
        cout << "Enter your choice: ";
        cin >> choice;
        cout << endl;

        switch (choice)
        {
        case 1:
            cout << "Enter element to be inserted: ";
            cin >> value;
            cout << "Enter key at which element to be inserted: ";
            cin >> key;
            hash.set(key, value);
            break;
        case 2:
            cout << "Enter key of the element to be searched: ";
            cin >> key;
            if (hash.get(key) == -999)
            {
                cout << "No element found at key " << key << endl;
            }
            else
            {
                cout << "Element at key " << hash.get(key) << " : ";
            }
            break;
        case 3:
            cout << "Enter key of the element to be deleted: ";
            cin >> key;
            deleted = hash.remove(key);
            if (deleted == -999)
            {
                cout << "Value not found for key: " << key << endl;
            }
            else
            {
                cout << "Value of deleted key: " << deleted << endl;
            }
            break;
        case 4:
            cout << "Load is: " << hash.load() << endl;
            break;
        case 5:
            exit(1);
            break;
        default:
            cout << "\nEnter correct option\n";
        }
    }
    return 0;
}

1 个答案:

答案 0 :(得分:0)

问题出在构造函数中的malloc中。由于你有一个双指针,你应该

{{1}}

您目前正在做的是将完整节点的空间分配给您需要的多个节点指针的空间。