为什么不同程序执行之间的哈希值不一致
Why are hash values inconsistent between different program executions?
作为研究项目的一部分,我正在测试我在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;
相关文章:
- boost::包含提升单元的元组的哈希值
- 如何使用 STL 哈希容器中的哈希值检索元素?
- 哈希函数中同一键的不同值和良好的哈希值排序
- 字符串单词的唯一哈希值
- 是否可以将哈希值作为编译时常数
- CMake检查下载文件的哈希值(MD5/SHA256)
- 正在将哈希值存储到int
- 如何计算没有标签信息的 mp3 文件的哈希值
- 如何定义函数序列的哈希值(C++)
- 为什么谓词版本的lower_bound和upper_bound传递迭代器值不一致
- C++-对象图的哈希值类似于boost::序列化
- 如何获取哈希值,C++ hash_map
- 在Qt中创建目录的哈希值
- 杂音哈希 - 哈希值不一致
- 逐行散列文件时错误的 md5 哈希值
- unordered_map - 哈希函数不起作用
- 为什么不同程序执行之间的哈希值不一致
- 如何有效地存储和排序生日攻击的哈希值
- 基本dll地址总是不同且哈希值不匹配
- HMAC-SHA1不返回期望的哈希值