c++哈希表和链表的访问冲突

C++ Access Violation With Hash Tables and Linked Lists

本文关键字:访问冲突 链表 哈希表 c++      更新时间:2023-10-16

所以我一直在尝试创建一个处理1000个链表的类,并最初声明指向它们的指针。

这是直接处理我的问题的代码:

struct node
{
    char name[40];
    char numb[12];
    node * next;
};
class hashTable
{
public:
    //Creates a table of 1000 pointers to linked-list nodes
    node * table[1000];
//Functions
void addNode(char name[40], char numb[12])
{
    node * temp;        //Initializes temp node as pointer
    temp = new node;    //Points temp node to a new node
    int hash = h(g(name));  //The hash of the key (name) used to check nodes
    temp = table[hash];     //sets the temporary node to the first node of the list
    while (temp->next != 0)
    {
//...

在while循环中,我得到错误"读取位置0xcccccd00"我不知道为什么它不能访问表成员,除非可能是因为这些值还没有初始化或什么?

您可能没有做两件事。首先,确保正确初始化哈希表以包含全空指针。其次,确保从哈希表中检索到的任何指针都是有效的优先于对其解引用:

第一期:

hashTable::hashTable() : table()
{
}

同时,你要确保这个东西被正确清理

hashTable::~hashTable()
{
    for (size_t i=0;i<sizeof(table)/sizeof(table[0]); ++i)
    {
        node *temp = table[i];
        while (temp)
        {
            node *victim = temp;
            temp = temp->next;
            delete victim;
        }
    }
}

第二期:

void addNode(const char *name, const char *numb)
{
    int hash = h(g(name));    //The hash of the key (name) used to check nodes
    node *temp = table[hash]; //sets the temporary node to the first node of the list
    if (temp)
    {
        // preexisting entry. walk that list looking for matching key.
        node **pp = &temp->next;
        while (temp)
        {
            if (0 == strcmp(temp->name, name))
                break;
            pp = &temp->next;
            temp = temp->next;
        }
        // link to last node if not found in list
        if (!temp)
            *pp = new node(name, numb);
    }
    else
    {   // no prior entry. create a new one and store it at table[hash].
        table[hash] = new node(name, numb);
    }
}
注意:上面的代码假设节点类被实现为
struct node
{
    char name[40];
    char numb[12];
    node * next;
    node(const char* name_, const char *numb_)
        : next()
    {
        strncpy(name, name_, sizeof(name)/sizeof(name[0])-1);
        name[ sizeof(name)/sizeof(name[0])-1 ] = 0;
        strncpy(numb, numb_, sizeof(numb)/sizeof(numb[0])-1);
        numb[ sizeof(numb)/sizeof(numb[0])-1 ] = 0;
    }
};

我个人会用std::string

如果hash值大于(或等于)1000,temp将指向无效区域

并且您正在泄漏由new node分配的内存,因为您正在覆盖temp变量。