Reputation: 113
I need to fill an integer-type variable (of arbitrary size) with data from /dev/urandom. With that in mind, I have the following piece of code:
std::fstream fstr("/dev/urandom", std::fstream::in | std::fstream::binary);
fstr.read(reinterpret_cast<char*>(&randomseed), sizeof(randomseed));
fstr.close();
(randomseed is the variable which I need to fill with random data).
Will this do the right thing (i.e. is it safe regardless of library implementation), or should I use some other *_cast?
Upvotes: 2
Views: 101
Reputation: 180235
It's NOT safe. Only the char
types are guaranteed to have no trap representations.
The "proper" solution is to wrap /dev/urandom
in a C++ <random>
engine, and use a std::uniform_int_distribution
.
Upvotes: 1