我在尝试将字符串哈希到哈希表时尝试调试哈希函数。以下代码是我的源文件,我还将发布valgrind错误消息。任何反馈错误都将非常感激。在3个函数中发布的是我收到错误的地方。在我的函数hashQ中我尝试传递给add_string函数my_hash_table和char * str,我得到的valgrind错误如下:再次提供任何帮助将非常感谢!!
==17194== Invalid read of size 8
==17194== at 0x400D63: lookup_string (hash.c:57)
==17194== by 0x400DF3: add_string (hash.c:76)
==17194== by 0x401187: display (queue.c:68)
==17194== by 0x400BE1: main (compare.c:85)
==17194== Address 0x5aa01ac58 is not stack'd, malloc'd or (recently) free'd
==17194==
==17194==
==17194== Process terminating with default action of signal 11 (SIGSEGV)
==17194== Access not within mapped region at address 0x5AA01AC58
==17194== at 0x400D63: lookup_string (hash.c:57)
==17194== by 0x400DF3: add_string (hash.c:76)
==17194== by 0x401187: display (queue.c:68)
==17194== by 0x400BE1: main (compare.c:85)
另外,我的hash.h文件如下:
#ifndef HASH_H
#define HASH_H
typedef struct _list_t_{
char *string;
struct _list_t_ *next;
} list_t;
typedef struct _hash_table_t_{
int size;
list_t **table;
} hash_table_t;
//creation of a hash_table
hash_table_t *create_hash_table(int size);
//hash function
unsigned long hash(char *str);
//string lookup
list_t *lookup_string(hash_table_t *hashtable, char *str);
//inserting a string
int add_string(hash_table_t *hashtable, char *str);
//Deleting a table
void free_table(hash_table_t *hashtable);
int count_strings(hash_table_t *hashtable);
#endif
unsigned long hash(char *str)
{
unsigned long hashval = 5381;
int c;
while((c = *str++))
hashval = ((hashval << 5) + hashval) + c; /* hashval * 33 + c */
return hashval;
}
list_t *lookup_string(hash_table_t *hashtable, char *str)
{
printf("1");
list_t *list;
printf("2");
unsigned int hashval = hash(str);
printf("3");
//go to the correct list based on the hash value and see if str is
//in the list. If it is, return a pointer to the list element.
// if not, the item isnt in the table, return NULL
for(list = hashtable->table[hashval]; list != NULL; list = list->next) {
if(strcmp(str, list->string) == 0)
return list;
}
return NULL;
}
int add_string(hash_table_t *hashtable, char *str)
{
list_t *new_list;
list_t *current_list;
unsigned int hashval = hash(str);
//allocate memory for list
if((new_list = malloc(sizeof(list_t))) == NULL)
return 1;
//check to see if the item already exist
current_list = lookup_string(hashtable, str);
//item already exists, dont insert it again
if(current_list != NULL) return 2;
//insert into list
new_list->string = strdup(str);
new_list->next = hashtable->table[hashval];
hashtable->table[hashval] = new_list;
return 0;
}
答案 0 :(得分:0)
如果有人在观看,我确实找到了答案,我的哈希函数使我的哈希值变大了,我在查询字符串函数中使用了它,它超出了我的哈希表的界限所以我是gdb和Valgrind的。我会弯曲我的讨厌的肌肉,现在走来走去。快乐编码!!!!