我在这里有一个哈希表,并且该程序试图通过搜索其哈希值被计算为其大写ascii值之和的单词的链表来查找字谜。
我看不出这段错误是怎么发生的,更不用说了解gdb
告诉我的内容。很明显它发生在anagramlookup()
,但我看不出如何。
以下是gdb
输出:
Program received signal SIGSEGV, Segmentation fault.
__strspn_sse2 ()
at ../sysdeps/x86_64/multiarch/../strspn.S:53
53 ../sysdeps/x86_64/multiarch/../strspn.S: No such file or directory.
(gdb) backtrace
#0 __strspn_sse2 ()
at ../sysdeps/x86_64/multiarch/../strspn.S:53
#1 0x0000000000400a0a in anagramlookup (
word=0x7fffffffe7c0 "you") at thirdfailure.c:66
#2 0x0000000000400c17 in main () at thirdfailure.c:121
(gdb) frame 2
#2 0x0000000000400c17 in main () at thirdfailure.c:121
121 anagramlookup(search);
(gdb) print search
$1 = "you\000\000\177\000\000\221I\336\367\377\177\000\000\000\000\000\000\000\000\000\000\020\232\377\367\377\177\000\000\001", '\000' <repeats 15 times>, "\001\000\000\000\377\177\000\000\310\341\377\367\377\177", '\000' <repeats 37 times>
段错误不会一直发生。如果要查找的单词是“post”,那么一切正常。但是当它是“你”时,就是我遇到段错误的时候。 “youu”不会给我一个段错误。我该如何解决问题?
这是我的代码:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
struct Hash *hashTable = NULL;
struct Node{
char val[100];
struct Node *next;
};
struct Hash{
int size;
struct Node *head;
};
struct Node* newnode(char* word){
struct Node *ptr = (struct Node*)malloc(sizeof(struct Node));
strcpy(ptr->val, word);
ptr->next = NULL;
return ptr;
}
void insertHash(char* word){
int index = hashmaker(word);
struct Node *ptr = newnode(word);
if(!hashTable[index].head){
hashTable[index].head = ptr;
hashTable[index].size = 1;
return;
}
else{
ptr->next = (hashTable[index].head);
hashTable[index].head = ptr;
hashTable[index].size++;
return;
}
}
void anagramlookup(char* word){
int index = hashmaker(word);
struct Node *ptr = hashTable[index].head;
if(ptr == NULL){
printf("we dont have any");
}
else{
while((ptr!= NULL)){
if(strlen(word)==strspn(word,ptr->val) &&
strlen(word)==strspn(ptr->val,word) &&
strlen(word)==strlen(ptr->val)){
if(strcmp(word,ptr->val) != 0){
printf("\n%s", ptr->val );
}
}
ptr = ptr->next;
}
}
}
int hashmaker(char* word){
int toreturn = 0, i, len;
len = strlen(word);
for(i = 0; i < len; i++){
toreturn += toupper(word[i]);
}
return toreturn;
}
int main(){
char search[100];
hashTable = (struct Hash *) malloc(sizeof(struct Hash));
FILE* dict = fopen("words2", "r");
if(dict == NULL) {
printf("dict is null");
exit(1);
}
// Read each line of the file, and print it to screen
char wordo[128];
while(fgets(wordo, sizeof(wordo), dict) != NULL) {
printf("%s", wordo);
wordo[strlen(wordo) - 1] = '\0';
insertHash(wordo);
}
printf("now enter your search: ");
fgets(search, sizeof(wordo), stdin);
search[strlen(search) - 1] = '\0';
anagramlookup(search);
return 0;
}
答案 0 :(得分:1)
hashTable是一个struct Hash数组,但尚未分配内存。你需要知道hashTable数组的大小,并在通过索引访问它之前为它分配内存。 hasTable [IDEX]。如果hashTable的大小为n,则按如下方式分配内存
hashTable = (struct Hash *) malloc(sizeof(struct Hash) * n);
如果您不知道尺寸,请尝试使用安全号码。例如,以下更改应解决崩溃
hashTable = (struct Hash *) malloc(sizeof(struct Hash) * 3000);