I have following code:
#include <cstring>
#include <boost/functional/hash.hpp>
#include <iostream>
int main(int argc, char **argv)
{
const char *str1 = "teststring";
// copy string
size_t len = strlen(str1);
char *str2 = new char[len+1];
strcpy(str2, str1);
// hash strings
std::cout << "str1: " << str1 << "; " << boost::hash<const char*>()(str1) << std::endl;
std::cout << "str2: " << str2 << "; " << boost::hash<const char*>()(str2) << std::endl;
delete[] str2;
return 0;
}
I always get the same hash for str1 (as expected). But str2 differs – in fact it returns a different hash every time I run the programm.
Can someone explain why?
As Linuxios suggested, it’s hashing the pointer value, not the string. I did a quick test with this code:
And here’s the output. Note that the string is different but since the pointer is the same the hash matches.
The only change you need to make is to tell boost it’s hashing a
std::stringand it will give you matching hashes. Your underlying data can remainchar*.Result: