2

So I've been trying to create a class that handles 1000 linked lists, and initially declares pointers to them.

This is the code that deals directly with my issues:

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)
    {
//...

Right at the while loop is where I get the error "Access violation reading location 0xcccccd00" I'm not sure why it can't access the table member, unless perhaps it is because these values have not been initialized or anything?

4

2 回答 2

2

你可能不会做两件事。首先确保您的哈希表已正确初始化为包含全空指针。其次,确保从哈希表中检索到的任何指针在取消引用之前都是有效的:

对于第一个问题:

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

于 2013-03-20T19:06:41.063 回答
0

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

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

于 2013-03-20T18:56:13.073 回答