gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 03:57:43 26 4
gpt4 key购买 nike

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

#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;

关于c++ - 为什么不同的程序执行之间哈希值不一致?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27813461/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com