C++ 为什么不同程序执行之间的哈希值不一致?
作为一个研究项目的一部分,我正在测试一些我在永远混乱的计算机上发现的哈希函数。该项目涉及页面缓存算法,散列行为本身直到现在才显得重要,但这更多是出于我自己的好奇心。为了进行测试,我使用以下代码:C++ 为什么不同程序执行之间的哈希值不一致?,c++,hash,C++,Hash,作为一个研究项目的一部分,我正在测试一些我在永远混乱的计算机上发现的哈希函数。该项目涉及页面缓存算法,散列行为本身直到现在才显得重要,但这更多是出于我自己的好奇心。为了进行测试,我使用以下代码: #include <iostream> #include <cstdlib> #include <string> using namespace std; unsigned oat_hash(void *key, int len); int main() {
#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;
}
程序执行2输出:
Enter a name: John Doe
Hash: 3085275063
Enter the name again: John Doe
Hash: 3085275063
我在同一个程序执行期间输入了相同的字符串并获得了相同的哈希值,但是为什么不同的程序执行的值会不同呢?不同的散列值不表示不同的数据吗?
std::string
的实现包含一个指针。您正在散列std::string
的内部内容,而不是std::string
的实际文本。在现代系统中,堆栈位置是随机化的,freestore分配也是随机化的,每次运行时都会生成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;
无符号oat_散列(void const*key,int len)
{
无符号字符常量*p=静态_转换(键);
//等等。
}
//...
难道我只运行了5次就得到了完全相同的输出吗?你可能进入了一个空间,但没有意识到。这是我最初的想法,但我检查了一下。我甚至使用了不同的输入,结果(对于不同的程序执行,得到不同的哈希值)是一样的;这是一个很好的解释和解决方案。如果我能投票的话,我当然会。真的很想知道+1.
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;