Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does std::hash give same result for same input for different compiled builds and different machines?

I have some random test parameters for which I need to calculate a hash to detect if I ran with same parameters. I might run the test using the same source recompiled at a different time or run on a different machine.

Even so I want to detect whether the same parameters were used for the run. Does std::hash give the same result for the same input for different compiled builds and different machines?

e.g.

std::hash<string>{}("TestcaseParamVal0.7Param0.4");

Will this always be a unique number?

like image 462
Nelson Pinto Avatar asked Jul 03 '18 00:07

Nelson Pinto


People also ask

Does hash produce same output for same input?

Hashing the same input produces the same digest or hash. The input of this function can be of any size. It can even be empty. The output is always of the same length and deterministic: it always produces the same result if given the same input.

Can different inputs have the same hash?

A hash function has no awareness of “other” items in the set of inputs. It just performs some arithmetic and/or bit-magic operations on the input item passed to it. Therefore, there's always a chance that two different inputs will generate the same hash value. Take the well-known hash function CRC32, for example.

Is hash output always the same?

Yes, a hash algorithm always produces the same output. If you use the same salt, this will also always produce the same output for a given input.

Can hash values be the same?

If two different inputs are having the same hash value, it is called a collision. Since hash functions have infinite input length and a predefined output length, there is a possibility of two different inputs that produce same hash value. Here is an example that displays different content, yet has the same SHA-1 value.


1 Answers

No, std::hash does not guarantee that the result will be the same across computers, builds, or even executions of the same build on the same computer. Your only guarantee is that during one execution, objects that are equal have the same hash. (There is, of course, no guarantee that objects that are unequal have different hashes.)

Some implementations go out of their way to change hash results between executions, as it mitigates denial of service risks due to the poor performance of hash tables in the presence of many keys with the same hash. This is explicitly allowed by the standard, which only guarantees that results are consistent for the duration of the program.

If you need repeatability between executions and machines, you can't use std::hash and must roll out your own equivalent.

like image 108
zneak Avatar answered Oct 02 '22 19:10

zneak