【问题标题】:Implementation of simple, non-cryptographic hash functions简单的非加密哈希函数的实现
【发布时间】:2020-08-08 12:16:26
【问题描述】:

我是编程新手,正在努力弄清楚如何使用简单的哈希函数。

例如,我将以下代码放在一起来测试 RS 哈希函数(用 C 语言),但我不断收到段错误。

也许我错误地实现了该函数...我尝试了其他一些简单的哈希函数(例如 PJW)并且也出现了段错误。

我确实删除了函数的一个原始参数(无符号整数长度)(因为我正在完成一个问题集,而我们的哈希函数的规范是它应该只接受一个 const 字符串作为输入),但我认为会很好,因为我 认为 这个参数是指字符串长度,我可以在函数内部使用 strlen 轻松获得它,而不是将其传递给函数。我尝试使用 valgrind 进行调试,但它没有显示任何内存泄漏。也许我缺少一些关于如何将外部代码合并到我自己的源代码中的基本知识。

unsigned int hash(const char *word);

int main(int argc, char *argv[])
{
    // Return error if string name missing from command line
    if (argc != 2)
    {
        printf("Usage: ./recover.c string name\n");
        return 1;
    }
    int i = hash(argv[2]);
    printf("%i\n", i);
}

unsigned int hash(const char *word) // RS Hashing function
{
    unsigned int b = 378551;
    unsigned int a = 63689;
    unsigned int hash = 0;
    unsigned int length = strlen(word);
    unsigned int i = 0;

    for (i = 0; i < length; word++, i++)
    {
        hash = hash * a + (*word);
        a = a * b;
    }

    return hash;
} 

提前感谢您的任何见解!知道我哪里出错了会很有帮助。

【问题讨论】:

  • 提示:如果argc == 2argv 的唯一可用索引是 0 和 1。
  • 多么愚蠢的错误。感谢举报!

标签: c hash hashtable


【解决方案1】:

我相信@Mat 已经知道了:

分段错误是由于您的 argc 条件造成的。如果将条件更改为 (argc https://onlinegdb.com/r1Udx0lYI)

另外,如果你对“简单的非加密哈希函数的实现”感兴趣,我邀请你看看下面的网站:

http://www.cse.yorku.ca/~oz/hash.html

【讨论】:

    猜你喜欢
    • 2018-07-12
    • 2021-01-23
    • 2013-05-05
    • 2013-01-02
    • 2016-03-25
    • 2011-09-01
    • 2010-09-20
    • 1970-01-01
    • 2021-11-19
    相关资源
    最近更新 更多