0

I was trying to make a hash table for my project but I keep getting bad access error. There is no mistake in syntax as compiler tells me. I think I have made a mistake in memory allocation but I can't see it. Any help is appreciated.

I get a bad access error in this loop:

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
}

And here is the all of the code:

#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);   
}
Boann
  • 48,794
  • 16
  • 117
  • 146
Mutlu
  • 13
  • 3

1 Answers1

0

You've declared the data_id array in hash_itself as an array of pointers to hash_value structs. Since those pointers are not initialized, it accesses invalid memory.

I think you wanted to create an array of the structs directly, in which case you want:

typedef struct hash_itself
{
    hash_values_t data_id[size];
}
Boann
  • 48,794
  • 16
  • 117
  • 146