为什么不同程序执行之间的哈希值不一致

Why are hash values inconsistent between different program executions?

本文关键字:哈希值 不一致 之间 执行 程序 为什么不      更新时间:2023-10-16

作为研究项目的一部分,我正在测试我在Eternally Confuzzled上找到的一些哈希函数。 该项目与页面缓存算法有关,哈希行为本身直到现在似乎都不重要,但这仍然更多地是为了我自己的好奇心。 为了进行测试,我使用以下代码:

#include <iostream>
#include <cstdlib>
#include <string>
using namespace std;
unsigned oat_hash(void *key, int len);
int main()
{
    string name;
    cout << "Enter a name: ";
    getline(cin, name);
    cout << "Hash: " << oat_hash(&name, sizeof(string)) << endl << endl;
    cout << "Enter the name again: ";
    getline(cin, name);
    cout << "Hash: " << oat_hash(&name, sizeof(string)) << endl << endl;
    return 0;
}
unsigned oat_hash(void *key, int len)
{
    unsigned char *p = (unsigned char*) key;
    unsigned h = 0;
    for (int i = 0; i < len; i++) {
        h += p[i];
        h += (h << 10);
        h ^= (h >> 6);
    }
    h += (h << 3);
    h ^= (h >> 11);
    h += (h << 15);
    return h;
}

程序执行 1 输出:

Enter a name: John Doe
Hash: 4120494494
Enter the name again: John Doe
Hash: 4120494494

程序执行 2 输出:

Enter a name: John Doe
Hash: 3085275063
Enter the name again: John Doe
Hash: 3085275063
我输入了相同的字符串,并在相同的程序执行

期间获得了相同的哈希值,但是为什么不同的程序执行的值会有所不同? 不同的哈希值不会表示不同的数据吗?

std::string的实现包含一个指针。您正在散列std::string的内部结构,而不是std::string的实际文本。在现代系统上,堆栈位置是随机的,自由存储分配也是随机的,每次运行它时都会产生不同的内部std::string

您可能希望像这样更改代码:

unsigned oat_hash(void const *key, int len)
{
    unsigned char const *p = static_cast<unsigned char const *>(key);
    // etc.
}
//...
cout << "Hash: " << oat_hash(name.c_str(), name.size()) << endl << endl;