Hi,
I seem to get a seg fault when i implement this hash function from 'Algorithms in C -Sedgewick' ....
I'm think it's more of my structuring, and pointer problems..
Code:
typedef struct {
char *key;
char *value;
} TableEntry;
typedef struct {
int table_size;
int num_items;
TableEntry *table;
} HashTable;
static HashTable *
hashtable_init(size_t size)
{
int i;
HashTable *newtable = safe_malloc(sizeof(HashTable));
newtable->table = safe_malloc(sizeof(TableEntry)*size);
newtable->table_size = size;
newtable->num_items = (int)size;
if(newtable == NULL)
{
fprintf(stderr, "hashtable_init() - NYI\n");
exit(EXIT_FAILURE);
}
/*allocate memory for word and key for each TableEntry*/
for(i=0; i<(int)size; i++){
newtable->table[i].key = safe_malloc(sizeof(char)*WORD_LEN);
newtable->table[i].value = safe_malloc(sizeof(char)*WORD_LEN);
}
/*Initialise all keys and values to be null character*/
for(i=0; i<(int)size; i++)
{
newtable->table[i].key = '\0';
newtable->table[i].value = '\0';
}
return newtable;
}
static void
hashtable_insert(HashTable *ht, char *key, char *value)
{
int hashval = hash_func(value, ht);
int M = ht->num_items;
while(ht->table[hashval].key != '\0')
hashval = (hashval+1) % M;
strcpy(ht->table[hashval].key, key);
strcpy(ht->table[hashval].value, value);
}
int hash_func(char *v, HashTable *ht)
{
int h = 0, a = 31415, b = 27183;
int M = ht->num_items;
/*Segmentation Fault happens in this loop*/
for(h=0; *v != '\0'; v++, a = a*b % (M-1))
h = (a*h + *v) % M;
return h;
}
static void
read_records(FILE *fp, HashTable *ht, char chomp(char*))
{
char key_buffer[MAX_STRING_SIZE];
char value_buffer[MAX_STRING_SIZE];
while (fgets(key_buffer, MAX_STRING_SIZE, fp) != NULL)
{
if (fgets(value_buffer, MAX_STRING_SIZE, fp) == NULL)
{
fprintf(stderr, "Badly formed input file");
exit(EXIT_FAILURE);
}
hashtable_insert(ht, chomp(key_buffer), chomp(value_buffer));
}
}
The chomp() function just replaces '\n' with '\0' from the input file
Thx!!!!