【发布时间】:2018-02-24 08:36:34
【问题描述】:
我真的很想知道是否有人不介意教育我了解我可能在这里错过的原则。我以为我已经涵盖了所有内容,但似乎我做错了什么。
下面的代码给了我一个分段错误,我不知道为什么?我在传递给fscanf的参数名称前添加&。
int word_size = 0;
#define HASH_SIZE 65536
#define LENGTH = 45
node* global_hash[HASH_SIZE] = {NULL};
typedef struct node {
char word[LENGTH + 1];
struct node* next;
} node;
int hash_func(char* hash_val){
int h = 0;
for (int i = 0, j = strlen(hash_val); i < j; i++){
h = (h << 2) ^ hash_val[i];
}
return h % HASH_SIZE;
}
bool load(const char *dictionary)
{
char* string;
FILE* dic = fopen(dictionary, "r");
if(dic == NULL){
fprintf(stdout, "Error: File is NULL.");
return false;
}
while(fscanf(dic, "%ms", &string) != EOF){
node* new_node = malloc(sizeof(node));
if(new_node == NULL){
return false;
}
strcpy(new_node->word, string);
new_node->next = NULL;
int hash_indx = hash_func(new_node->word);
node* first = global_hash[hash_indx];
if(first == NULL){
global_hash[hash_indx] = new_node;
} else {
new_node->next = global_hash[hash_indx];
global_hash[hash_indx] = new_node;
}
word_size++;
free(new_node);
}
fclose(dic);
return true;
}
dictionary.c:25:16: runtime error: left shift of 2127912344 by 2 places cannot be represented in type 'int'
dictionary.c:71:23: runtime error: index -10167 out of bounds for type 'node *[65536]'
dictionary.c:73:13: runtime error: index -10167 out of bounds for type 'node *[65536]'
dictionary.c:75:30: runtime error: index -22161 out of bounds for type 'node *[65536]'
dictionary.c:76:13: runtime error: index -22161 out of bounds for type 'node *[65536]'
Segmentation fault
【问题讨论】:
-
调试器告诉我们错误发生在哪一行?
-
你确定
new_node->word够长吗 -
关于:
while(fscanf(dic, "%ms", &string) != EOF){1) '%ms' 无效,2) 当使用 '%s' 输入格式说明符时,始终包含一个比长度小一的 MAX CHARACTERS 修饰符输入缓冲区,因为“%s”总是将 NUL 字节附加到输入。这避免了缓冲区溢出的任何可能性。这种溢出是未定义的行为,可能导致段错误事件。顺便说一句:发布的代码缺少必要的分配(可能通过malloc())指针string指向的任何缓冲区。 -
您的错误不在显示的代码中。了解
'm'修饰符%s是不可移植的。它甚至是在基于 Linux 的编译器中定义的实现。