Not sure on hash table memory allocations
I'm trying to work on a program that inputs entries from a file and then builds a hash table. I'm a little new to programming so I know I do not have the best form. I only submitted the code that I think might be the problem...
This code compiles but then has runtime errors and every time I look to see if the current hash table index is NULL it has a large number like a memory address. If anyone could give me some advice on what I might be doing wrong with the add and search functions that would be so nice... :)
PHP Code:
[CODE]
struct ht_entry { /* an entry (node) in hash table */
char ht_name[NAME_LENGTH + 1]; /* name in hash table */
int ref_count; /* number of references to the name */
struct ht_entry *next;
};
struct ht_entry *hash_tbl[BKT_SIZE]; /* bucket directory (hash index) */
int search(char *name_ptr, int *ind_ptr) /* name to be searched , hash index (index into the hash table) */
{
struct ht_entry *tmp; /* declare tmp */
tmp = malloc(sizeof(*tmp)); /* allocate memory for tmp */
tmp=hash_tbl[*ind_ptr]; /* sets to the head of hash_tbl */
printf("SEARCH ");
while(tmp!=NULL) /* while tmp is not NULL */
{
if((strcmp(tmp->ht_name, name_ptr))==0) /* if hash_tbl name is equal to current name return true (FOUND) */
{
return TRUE;
}
tmp=tmp->next;
}
return FALSE; /* else return false (NOT FOUND) */
}/* end of search */
void add(char *name_ptr,int *ind_ptr) /* (pointer to name, pointer to hash index) THIS ADDS NODE TO HASH TABLE */
{
struct ht_entry *head; /* declare head */
head = malloc(sizeof(*head)); /* allocate memory for head */
if(hash_tbl[*ind_ptr]==NULL) /* if hash_tbl[index] is NULL initialize a new node for index */
{
hash_tbl[*ind_ptr] = malloc(sizeof(*hash_tbl)); /* allocate memory for hash_tbl[hash_index] if it's NULL */
strcpy(hash_tbl[*ind_ptr]->ht_name, name_ptr);
hash_tbl[*ind_ptr]->ref_count=0;
printf("It was NULL." );
}
else /* else initialize head then link to hash_tbl[index] */
{
strcpy(head->ht_name, name_ptr);
head->ref_count=0;
head->next=hash_tbl[*ind_ptr];
hash_tbl[*ind_ptr]=head;
printf("It wasn't NULL. ");
}
printf("It's been added!\n");
}//end add
/*
Sample Input:
DEF GONE
DEF KMN127
DEF EGG
DEF VAN
DEF AKK
DEF EGG
USE VAN
USE AKK
USE JEEP
USE AKK
DEF FUN
DEF ALI
USE KMN127
Sample Output:
Input Data
Command Name
DEF GONE
DEF KMN127
DEF EGG
DEF VAN
DEF AKK
DEF EGG *** Duplicate Name ***
USE VAN
USE AKK
USE JEEP *** Undefined Name ***
USE AKK
DEF FUN
DEF ALI
USE KMN127
*/
[/CODE]