Reputation: 1
Memory exception When inserting a value into a hash table, I need to build a function that will insert values into my hash table but there is a memory problem because the chain threw me an anomaly I would love a solution
hashtable.h
struct HashTableElement
{
int key;
LinkedList* chain;
};
typedef struct HashTable HashTable;
struct HashTable
{
HashTableElement* hashTable;
int hashFunction;
int tableSize;
int cellsTaken;
int numOfElements;
};
linked list.h
typedef struct LinkedList LinkedList;
struct LinkedList {
char* data;
LinkedList* next;
};
hash table.c
HashTable* initTable(int tableSize, int hashFunction)
{
HashTable* table = (HashTable*)malloc(sizeof(HashTable));
table->tableSize = tableSize;
table->hashFunction = hashFunction;
if (table == NULL || tableSize < 1)
{
printf("EROR with malloc in initTable.");
exit(1);
}
table->hashTable = malloc(sizeof(HashTableElement) * tableSize);
int i;
for (i = 0; i < hashFunction; i++) {
table->hashTable[i].key = NULL;
table->hashTable[i].chain = NULL;
}
return table;
}
int insert(HashTable* ht, char* str)
{
HashTable* temp;
int h = hash(str, ht);
int i = 0;
while (ht->hashTable[h].key != 0 && (i < ht->tableSize)) {
if (ht->hashTable[h].key == *str) {
ht->hashTable[h].key = *str;
return; /* break is intended to quit the loop, but actually we want to exit the function altogether */
}
h = (h + 1) % ht->tableSize; /* changed 11 to the size specified */
i++; /* advance the loop index */
}
if (ht->hashTable[h].key == 0) {
ht->hashTable[h].chain->data = *str;
return 1;
}
return 0;
}
the problem with insert function in ht->hashTable[h].chain->data = *str; how I can solve the exception there?
Upvotes: 0
Views: 147
Reputation: 11
I suggest to take a course in basic C programming before continuing with implementing a hash table. There are numerous errors and just generic weird things, of the top of my hat:
Beyond these basic problems, the problem you are asking about is that chain will be NULL. If you use ...chain->data, you will dereference a NULL pointer, which is bad.
The real problem is that you don't seem to understand linked lists nor C memory management, which are a prerequisite for implementing more complicated structures, such as hash tables, so I would suggest you take a step back and start with a basic C course before continuing like this.
Upvotes: 1