【问题标题】:Hash table in C always yields Seg faultC中的哈希表总是产生Seg错误
【发布时间】:2015-09-06 06:20:03
【问题描述】:

我正在尝试使用 C 编程语言开发一个哈希表,该哈希表总是因段错误而失败。我正在尝试进行单独的链接,因此我创建了一个具有两个属性的结构:word 和 next。这个词是一个 char* 和 next 一个指向下一个节点的指针,最终创建一个包含链表数组的哈希表。

typedef struct node 
{
    char* word;
    struct node* next;

}node;

node* table[26]; 

在此之后,我使用一个简单地索引到表中的散列函数来索引到表中。

你有解决办法吗?

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <cs50.h>

typedef struct node 
{
    char* word;
    struct node* next;

}node;

node* table[26]; 


int hash(char* key);
void index();

int main(int argc, char* argv[])
{
    index();

    return 0; 
}

int hash(char* key)
{
    int hash = toupper(key[0]) - 'A';
    int res = hash % 26;

    return res;
}

void index()
{   
    printf("Insert a word: ");
    char* k = GetString();    


    node* predptr = malloc(sizeof(node));
    node* newptr = malloc(sizeof(node));

    for(int i = 0; i < 26; i++)
    {
        if(hash(k) == i)
        {
            predptr = table[0];

            predptr->next = newptr;

            newptr = predptr;

            break;
        }

        else
        {

        }
    }


}

【问题讨论】:

  • 您的第一句话听起来好像段错误是故意的。您的意思可能是“它总是失败”。
  • predptr = table[0]; - 你只是 (a) 泄露了内存,并且 (b) 将 NULL 放在了 predptr 中。随后的 predptr-&gt;next = ... 取消引用 NULL 并使您的进程崩溃。
  • 编译时包含所有警告和调试信息 (gcc -Wall -Wextra -g)。然后学习如何使用调试器,例如gdb(你需要有这个技能)。

标签: c hash cs50


【解决方案1】:
typedef struct node 
{
    char* word;
    struct node* next;

}node;

node* table[26]; 

table 是一个包含 26 个指针的数组,全部初始化为 NULL

特别是 table[0] 是一个 NULL 指针,您尝试取消引用它

            predptr = table[0];

            predptr->next = newptr; // dereference NULL pointer
            // NULL->next

【讨论】:

    【解决方案2】:

    您创建了一个包含 26 个指向 node 结构的指针的表,但没有为它们分配内存。此外,尚不清楚您的 GetString() 方法的作用以及如何管理它返回的字符串的内存。你必须使用你的(不完整的)索引方法(前提是你在那里正确分配了必要的对象)而不是仅仅调用 table[ha]-&gt;word = word; ,因为 tabel[ha] 没有指向任何地方。

    【讨论】:

    • GetString 是 CS50 的库函数。
    【解决方案3】:
    1. 如果你正在对 word 进行散列,则将散列函数更改为

      int hash(char *k){ int i=0; for (;i<strlen(k) ;++i ){ //apply hashing technique } }

    2. 当你使用时,你的表有 26 个 NULL 指针

      predptr = table[0]; predptr->next = newptr;

    这里 predptr 变为 NULL 然后你正在寻找它的 next 指针,这会导致分段错误。

    1. 为了提高索引性能,您不必搜索散列索引,只需转到该索引

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-15
      • 2020-07-16
      • 1970-01-01
      • 1970-01-01
      • 2012-11-19
      • 1970-01-01
      • 2016-08-13
      • 1970-01-01
      相关资源
      最近更新 更多