哈希表实现不良访问错误

时间:2014-12-20 19:35:13

标签: c hashtable

我正在尝试为我的项目创建一个哈希表,但我一直遇到错误的访问错误。编译器告诉我,语法没有错误。我认为我在内存分配方面犯了一个错误但我无法看到它。任何帮助表示赞赏。

我在这个循环中遇到错误的访问错误:

hash_itself_p hash_table = (hash_itself_p)malloc(sizeof(hash_itself_t));
for (i = 0; i < 50; i++)
{
    hash_table->data_id[i]->id = -1; // EXC_BAD_ACCESS here
}

以下是所有代码:

#include <stdio.h>
#include <stdlib.h>
#define size 50

typedef struct hash_value
{
    int id;
    int data;
    int key;
} hash_values_t[1], *hash_values;

typedef struct hash_itself
{
    hash_values data_id[size];
} hash_itself_t[1], *hash_itself_p;

int hash_key(int n)
{   
    return ( n*n + 2*n ) % size;
} 

int hash_id(int n)
{
    return n % size;
}

void insert(hash_itself_p hash_table, int person)
{
    int id;
    int key;

    key = hash_key(person);
    id = hash_id(key);

    if (hash_table->data_id[id]->id == -1)
    {
        hash_table->data_id[id]->id = id;
        hash_table->data_id[id]->data = person;
    } 
    else
    {
        int block = id;
        while (hash_table->data_id[block%50]->id != -1)
        {
            block++;
            if (block%50 == id) return;
        }        
        hash_table->data_id[block]->id = id;
        hash_table->data_id[block]->data = person;
    }    
}

void display(hash_itself_p hash_table)
{
    int i;
    for (i = 0; i < size; i++)
    {
        printf("id = %d, data = %d, key = %d \n", hash_table->data_id[i]->id, hash_table->data_id[i]->data, hash_table->data_id[i]->key);
    }
}

int main()
{
    int i;  
    hash_itself_p hash_table = (hash_itself_p)malloc(sizeof(hash_itself_t));
    for (i = 0; i < 50; i++)
    {
        hash_table->data_id[i]->id = -1;
    }
    insert(hash_table, 30);
    display(hash_table);   
}

1 个答案:

答案 0 :(得分:0)

您已将data_id中的hash_itself数组声明为指向hash_value结构的指针数组。由于这些指针未初始化,因此会访问无效内存。

我认为你想直接创建一个结构数组,在这种情况下你想要:

typedef struct hash_itself
{
    hash_values_t data_id[size];
}
相关问题